`Math.random()` 回傳 `[0, 1)` 區間浮點數。要獲得 `[min, max]` 區間**整數**:
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 1 ~ 10
Math.floor(Math.random() * 10) + 1; // 錯誤!最大只能產生 10 (若 random=0.999 → 9.99 → floor=9 +1=10) ✓ 但邊界易混淆
Math.floor(Math.random() * (10 - 1 + 1)) + 1; // 正確通用寫法
// 2 ~ 10
Math.floor(Math.random() * 9) + 2; // 9 = 10-2+1
// 3 ~ 11
Math.floor(Math.random() * 9) + 3; // 9 = 11-3+1
/**
* 產生 [min, max] 之間的隨機整數 (含邊界)
* @param {number} min - 最小值
* @param {number} max - 最大值
* @returns {number}
*/
function randomInt(min, max) {
if (min > max) [min, max] = [max, min]; // 自動交換
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 使用
console.log(randomInt(1, 10)); // 1-10
console.log(randomInt(10, 1)); // 同樣 1-10 (自動交換)
console.log(randomInt(-5, 5)); // -5 到 5
console.log(randomInt(100, 200)); // 100-200
function randomFloat(min, max) {
return Math.random() * (max - min) + min;
}
function randomChoice(arr) {
return arr[Math.floor(Math.random() * arr.length)];
}
var colors = ['red', 'green', 'blue'];
console.log(randomChoice(colors)); // 隨機顏色
function weightedRandom(items, weights) {
var total = weights.reduce((a, b) => a + b, 0);
var r = Math.random() * total;
for (var i = 0; i < items.length; i++) {
if (r < weights[i]) return items[i];
r -= weights[i];
}
}
// 70% 紅, 20% 綠, 10% 藍
weightedRandom(['red','green','blue'], [0.7, 0.2, 0.1]);
// 適用於 Token、驗證碼、加密金鑰
function secureRandomInt(min, max) {
var range = max - min + 1;
var bytes = new Uint32Array(1);
var maxUint32 = 0xFFFFFFFF;
var threshold = maxUint32 - (maxUint32 % range); // 拒絕採樣避免模數偏差
do {
window.crypto.getRandomValues(bytes);
} while (bytes[0] >= threshold);
return min + (bytes[0] % range);
}
| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
| `Math.random() * max` | 最大值 max-1,且為浮點數 | `Math.floor(Math.random() * max)` → 0 到 max-1 |
| `Math.round(Math.random() * max)` | 邊界 0 和 max 機率只有其他數字一半 | 用 `floor` + `+ min` |
| `Math.random() * (max - min) + min` | 不含 max,且為浮點數 | 整數用 `floor(...) + min` |
// 避免函式呼叫開銷,熱路徑可內聯
var r = Math.random();
var val = (r * 10 | 0) + 1; // 位元運算 |0 等同 Math.floor 但更快 (僅限 32 位整數範圍)
掌握 `Math.floor(Math.random() * (max - min + 1)) + min` 通用公式,並理解邊界條件與浮點數精度限制。安全性敏感場合請改用 `crypto.getRandomValues()`。