Math.ceil(); //向上取整。 Math.floor(); //向下取整。 Math.round(); //四捨五入。 Math.random(); //0.0 ~ 1.0 之間的一個偽隨機數。【包含0不包含1】 //比如0.8647578968666494 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,兩端的分布區間只有中間各值的一半。
這個功能在生成驗證碼或隨機選中某個選項時非常實用。
//生成從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);
以上就是關於 JavaScript 生成隨機數的完整解析,希望對你有所幫助。