JS中生成隨機數

一、Math 對象方法:

Math.ceil();  //向上取整。
Math.floor();  //向下取整。
Math.round();  //四捨五入。
Math.random();  //0.0 ~ 1.0 之間的一個僞隨機數。【包含0不包含1】 //好比0.8647578968666494

1.一、實例說明:

Math.ceil(Math.random()*10);      // 獲取從1到10的隨機整數 ,取0的機率極小。

Math.round(Math.random());   //可均衡獲取0到1的隨機整數。

Math.floor(Math.random()*10);  //可均衡獲取0到9的隨機整數。

Math.round(Math.random()*10);  //基本均衡獲取0到10的隨機整數,其中獲取最小值0和最大值10的概率少一半。

//由於結果在0~0.4 爲0,0.5到1.4爲1  ...  8.5到9.4爲9,9.5到9.9爲10。因此頭尾的分佈區間只有其餘數字的一半。

 

生成[n,m]的隨機整數的函數html

//生成從minNum到maxNum的隨機數
function randomNum(minNum, maxNum) {
  switch (arguments.length) {
    case 1:
      return parseInt(Math.random() * minNum + 1, 10);
      break;
    case 2:
      return parseInt(Math.random() * ( maxNum - minNum + 1 ) + minNum, 10);
      //或者 Math.floor(Math.random()*( maxNum - minNum + 1 ) + minNum );
      break;
    default:
      return 0;
      break;
  }
} 

Math.random() 生成 [0,1) 的數,因此 Math.random()*5 生成 {0,5) 的數。dom

parseInt() 能夠簡單理解成返回捨去參數的小數部分後的整數,因此 parseInt(Math.random()*5) 生成的是 [0,4] 的隨機整數。函數

 

原文連接:http://www.cnblogs.com/starof/p/4988516.htmlspa