Math对象
1.min()和max()方法
这两个方法都可以接收任意多个数值参数,例子如下:
var max=Math.max(3,54,32,16);
alert(max); //54
var min=Math.min(3,54,32,16);
alert(min); //3
要找到数组中的最大或最小值,可以像下面这样使用apply()方法。
var values=[1,2,3,4,5,6,7,8];
var max=Math.max.apply(Math,values);
这个技巧的关键是把Math对象作为apply()的第一个参数,从而正确地设置this值。然后可以将任何数组作为第二个参数。
2.舍入方法
Math.ceil()、Math.floor()、Math.round()
alert(Math.ceil(25.9)); //26
alert(Math.ceil(25.5)); //26
alert(Math.ceil(25.1)); //26
alert(Math.floor(25.9)); //25
alert(Math.floor(25.5)); //25
alert(Math.floor(25.1)); //25
alert(Math.round(25.9)); //26
alert(Math.round(25.5)); //26
alert(Math.round(25.1)); //25
3.random()方法
Math.random()方法返回大于等于0小于1的一个随机数。
值=Math.floor(Math.random()*可能值的总数+第一个可能的值)
如果想选择一个1到10之间的数值,代码如下:
var num=Math.floor(Math.random()*10+1);
如果想选择一个2到10之间的数值,代码如下:
var num=Math.floor(Math.random()*9+2);
多数情况下,可以通过一个函数来计算可能值的总数和第一个可能的值,例如:
function selectFrom(lowerValue,upperValue){
var choices=upperValue-lowerValue+1;
return Math.floor(Math.random()*choices+lowerValue);
}
var num=selectFrom(2,10);
alert(num); //介于2和10之间(包括2和10)的一个值
利用这个函数,可以方便地从数组中随机取出一项,例如:
var colors=["red","blue","yellow","black","purple"];
var color=colors[selectFrom(0,colors.length-1)];
alert(color); //可能是数组中包含的任何一个字符串