JS數據類型之Math對象

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);       //可能是數組中包含的任何一個字符串
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章