天天看點

js 生成随機數

我的封裝

/**
*擷取随機數
* minNum:最小值
* maxNum:最大值
*/
var randomNum=function (minNum,maxNum){ 
     return parseInt(Math.random()*(maxNum-minNum+1)+minNum,10); 
  };


//調用  1-20的随機數
randomNum(1,20);      

js 可以使用 Math(算數) 對象來實作随機數的生成。

需要了解的 Math 對象方法

方法 描述
​​ceil(x)​​ 對數進行上舍入,即向上取整。
​​floor(x)​​ 對 x 進行下舍入,即向下取整。
​​round(x)​​ 四舍五入。
​​random()​​ 傳回 0 ~ 1 之間的随機數,包含 0 不包含 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] 的随機整數

函數功能:生成 [n,m] 的随機整數。

在 js 生成驗證碼或者随機選中一個選項時很有用。

//生成從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); 
        break; 
            default: 
                return 0; 
            break; 
    } 
}      

過程分析:

Math.random() 生成 [0,1) 的數,是以 Math.random()*5 生成 {0,5) 的數。

通常期望得到整數,是以要對得到的結果處理一下。

parseInt(),Math.floor(),Math.ceil() 和 Math.round() 都可得到整數。

parseInt() 和 Math.floor() 結果都是向下取整。

是以 Math.random()*5 生成的都是 [0,4] 的随機整數。

是以生成 [1,max] 的随機數,公式如下:

// max - 期望的最大值
parseInt(Math.random()*max,10)+1;
Math.floor(Math.random()*max)+1;
Math.ceil(Math.random()*max);      

是以生成 [0,max] 到任意數的随機數,公式如下:

// max - 期望的最大值
parseInt(Math.random()*(max+1),10);
Math.floor(Math.random()*(max+1));      

是以希望生成 [min,max] 的随機數,公式如下:

// max - 期望的最大值
// min - 期望的最小值
parseInt(Math.random()*(max-min+1)+min,10);
Math.floor(Math.random()*(max-min+1)+min);