更新時間:2021-04-06 21:33:27 來源:動力節(jié)點 瀏覽1743次
生成隨機數(shù)無論是在Java還是在JavaScript中都是非常基礎的內(nèi)容,在JavaScript中可以通過Math.random()函數(shù)來生成0~1的隨機數(shù),也可以通過設置函數(shù)的值使其生成任意范圍的隨機數(shù)或者是各不相同的隨機數(shù)。本文我們就來通過實例講解JavaScript生成隨機數(shù),為大家不再為之花費心思。
在JavaScript中可以通過Math.random()函數(shù)產(chǎn)生一個0~1之間的隨機數(shù),但是這往往滿足不了我們平時的需求。Math.random函數(shù)就不像php的rand函數(shù)一樣可以生成指數(shù)范圍的數(shù)據(jù)了,math.random只是生成了一個偽隨機數(shù),之后還要經(jīng)過我們處理才行。但是我們可以通過其他方法來使其產(chǎn)生我們想要的隨機數(shù)。本文為大家分享的是通過Math.random()函數(shù)產(chǎn)生隨機數(shù),具有一定的參考作用,希望對大家有所幫助。
Math.round(Math.random());
如果我們想設置在指定范圍里的隨機數(shù)也可通過以上的函數(shù)生成
例:生成8~100之間的隨機數(shù)
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script>
var num=Math.floor(Math.random()*100+8);
document.write(num);
</script>
</head>
<body>
</body>
</html>
如果你想生成10到100范圍的話只需要將后面的數(shù)字8改為10就可以了,通過上述方法我們就可以實現(xiàn)自定義范圍內(nèi)隨機數(shù)的產(chǎn)生了
2.生成不重復的隨機數(shù)
有時可以通過特定的方法來產(chǎn)生隨機數(shù)但是它們之間不會重復,如下所示:
script>
// 定義存放生成隨機數(shù)的數(shù)組
var array=new Array();
// 循環(huán)N次生成隨機數(shù)
for(var i = 0 ; ; i++){
// 只生成10個隨機數(shù)
if(array.length<10){
generateRandom(10);
}else{
break;
}
}
// 循環(huán)遍歷隨機數(shù)數(shù)組
for(var i = 0 ; i < array.length; i++){
document.write(array[i]);
}
// 生成隨機數(shù)的方法
function generateRandom(count){
var rand = parseInt(Math.random()*count);
for(var i = 0 ; i < array.length; i++){
if(array[i] == rand){
return false;
}
}
array.push(rand);
}
</script>
結果會出現(xiàn)一組符合我們要求的隨機數(shù),我們每刷新一次就會顯示出一組新的隨機數(shù),但我們可以看出每次生成的是個隨機數(shù)都各不相同。
利用 parseInt()、Math.floor() 或者 Math.ceil()進行四舍五入處理
我們看到,直接使用Math.random()方法,生成的是一個小于1的數(shù),所以:
Math.random()*5
得到的結果是一個小于5的隨機數(shù)。而我們通常希望得到的是0-5之間的整數(shù),所以我們需要對得到的結果四舍五入處理一下,從而得到我們期望的整數(shù)。parseInt()、Math.floor()和Math.ceil()都可以起到四舍五入的作用。
var randomNum = Math.random()*5;
alert(randomNum); // 2.9045290905811183
alert(parseInt(randomNum,10)); // 2
alert(Math.floor(randomNum)); // 2
alert(Math.ceil(randomNum)); // 3
由測試的代碼我們可以看到,parseInt()和Math.floor()的效果是一樣的,都是向下取整數(shù)部分。所以parseInt(Math.random()*5,10)和Math.floor(Math.random()*5)都是生成的0-4之間的隨機數(shù),Math.ceil(Math.random()*5)則是生成的1-5之間的隨機數(shù)。
生成指定范圍數(shù)值隨機數(shù)
所以,如果你希望生成1到任意值的隨機數(shù),公式就是這樣的:
// max - 期望的最大值
parseInt(Math.random()*max,10)+1;
Math.floor(Math.random()*max)+1;
Math.ceil(Math.random()*max);
如果你希望生成0到任意值的隨機數(shù),公式就是這樣的:
// max - 期望的最大值
parseInt(Math.random()*(max+1),10);
Math.floor(Math.random()*(max+1));
如果你希望生成任意值到任意值的隨機數(shù),公式就是這樣的:
// min - 期望的最小值
parseInt(Math.random()*(max-min+1)+min,10);
Math.floor(Math.random()*(max-min+1)+min);
看到這里,相信我們對于JavaScript如何生成隨機數(shù)的疑惑迎刃而解,我們可以針對不同的要求生成不同性質的隨機數(shù)。在本站的JavaScript教程中還會給出采用其他函數(shù)生成隨機數(shù)的方法,我們可以由此舉一反三,推導出更多的方法。