DIV CSS 佈局教程網

Math.random:產生 0 到 1 之間的隨機數
編輯:關於JavaScript     

Math.random() 回傳一個大於等於 0、小於 1 的浮點數。它是 JavaScript 所有隨機行為的起點。

基本範例

<!DOCTYPE html>
<html>
<body>
<p id="demo">Click the button to display a random number.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
    document.getElementById("demo").innerHTML = Math.random();
}
</script>
</body>
</html>

怎麼轉成其他範圍

因為範圍固定是 [0, 1),只要乘上倍率再取整數,就能換算成任意區間:

// 0 到 9 的整數
Math.floor(Math.random() * 10);

// 1 到 6(骰子)
Math.floor(Math.random() * 6) + 1;

// min 到 max 之間的整數(含兩端)
function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

// min 到 max 之間的小數
Math.random() * (max - min) + min;

兩個容易出錯的地方:一是 Math.random() 回傳值不會等於 1,所以乘完之後若用 Math.round 會讓兩端的機率只有中間的一半,取整數時請一律用 Math.floor;二是 Math.random() 並非密碼學安全的隨機數,若要做 token、Session ID、加密用途,請改用 window.crypto.getRandomValues() 或 Node 的 crypto.randomBytes()。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved