JavaScript生成隨機數的方法


一,函數

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。所以頭尾的分布區間只有其他數字的一半。

 

二,生成【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);


 四,成績在60~100的隨機數

案例一:頁面輸出區域和控制台產生的隨機數不一致

 

相關的代碼及效果圖如下所示:

<script> function shy(){ console.log(60+parseInt(41*Math.random())) document.write(60+parseInt(41*Math.random())+",") } setInterval("shy()",200) </script>

 

效果圖:

 

 

案例二:頁面輸出區域和控制台產生的隨機數一致

<script> var bl function shy(){ bl=60+parseInt(41*Math.random()) document.write(bl+",") console.log(bl) } setInterval("shy()",260) </script>

 

效果圖:

 

 

      希望有所幫助!!!!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM