js獲取隨機數
<link rel="stylesheet" href="https://js.how234.com/third-party/SyntaxHighlighter/shCoreDefault.css" type="text/css" /><script type="text/javascript" src="https://js.how234.com/third-party/SyntaxHighlighter/shCore.js"></script><script type="text/javascript"> SyntaxHighlighter.all(); </script>
js獲取隨機數怎麼操作?一起來看看小編今天的分享吧!
JavaScript可以使用 Math(算數) 對象來實現隨機數的生成。Math 對象用於執行數學任務。且Math 對象並不像 Date 和 String 那樣是對象的類,因此沒有構造函數 Math()。
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);