Math.random() 回傳一個 0(含)到 1(不含)之間的浮點數。它本身範圍很窄,真正實用的是把它換算成任意區間的整數。
<!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>
// [min, max) 之間的整數
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
// [min, max] 之間的整數(含兩端)
function randomIntInclusive(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 指定範圍內的浮點數
function randomFloat(min, max) {
return Math.random() * (max - min) + min;
}
randomInt(1, 7); // 1 到 6,模擬骰子
randomIntInclusive(1, 7); // 1 到 7
為什麼一定要搭配 Math.floor 而不是 Math.round?因為 Math.round 會讓中間的數字涵蓋的區間比兩端寬一倍(例如 0 只涵蓋 [0, 0.5),而 1 涵蓋 [0.5, 1.5)),導致分佈不均。這是最常見的隨機數 bug。
function pick(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
// 洗牌(Fisher-Yates,請勿用 sort(() => 0.5 - Math.random()),分佈不均)
function shuffle(arr) {
var a = arr.slice();
for (var i = a.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var t = a[i]; a[i] = a[j]; a[j] = t;
}
return a;
}
Math.random() 不是密碼學安全的亂數,它的內部狀態可被推導,因此不可用於產生權杖、Session ID、重設密碼連結或任何安全相關的值。這類需求請改用 crypto.getRandomValues()(瀏覽器)或 Node 的 crypto.randomInt() / randomUUID()。