您的位置:首页 > Web前端 > JavaScript

js--引用类型单体内置对象--Math,随机数生成

2016-04-07 18:45 513 查看
内置对象:

在所有代码执行之前,作用域中就可以存在两个内置对象:Global和Math。

这些对象在ECMAScript执行之前就已经纯在了,开发者不用显示的实例化内置对象。

1.Math对象

1.Math对象的属性

Math.E

Math.LN2

Math.LOG2E

Math.PI等

2.Math对象的方法

2.1min()和max()

alert(Math.max(3,54,32));//54
alert(Math.min(3,54,32));//3


2.2舍入方法

Math.ceil()向上舍入为最接近的整数

Math.floor()向下舍入为最接近的整数

Math.round()四舍五入

alert(Math.ceil(25.9));//26
alert(Math.ceil(25.1));//26
alert(Math.floor(25.9));//25
alert(Math.floor(25.1));//25
alert(Math.round(25.9));//26
alert(Math.round(25.1));//25


2.3random()方法

Math.random()是返回大于等于0小于1的一个随机数

//某个范围内随机选择一个整数值
值 = Math.floor(Math.random()*可能值的总数 + 第一个可能的值);


//eg:想选择1-10的值
var num = Math.floor(Math.random()*10 + 1);


//generate a random array between 10-100
var array = [];
for(var i = 0;i < 60;i++){
array[i] = Math.floor(Math.random() * 91 + 10);
}


//随机选择数组中的元素
function makePhrase {
var word1 = ["ase","ewr","iuoh","zxc","ou"];
var word2 = ["cvbw","ar","icxv","erxc","opsdf];
var word3 = ["bv","eer","iua","zkyh","af"];
//随机生成的一个短语
var rand1 = Math.floor(Math.random()*word1.length);
var rand2 = Math.floor(Math.random()*word2.length);
var rand3 = Math.floor(Math.random()*word2.length);
var phrase = word1[rand1]+" "+word2[rand2]+" "+word3[rand3];
}


2.4其他方法

Math.tan(x)

Math.cos(x)

Math.aqrt(x)等
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: