| 需求 | 公式 | 示例 |
| [0, n) 整數 | Math.floor(Math.random() * n) | Math.floor(Math.random() * 6) → 0~5 |
| [min, max] 整數 | Math.floor(Math.random() * (max - min + 1)) + min | 擲骰子 1~6 |
| [min, max) 浮點數 | Math.random() * (max - min) + min | 隨機價格 10.00~99.99 |
| 布林值 (50%) | Math.random() < 0.5 | 隨機真假 |
| 加權隨機 | 累積權重數組 + 二分查找 | 抽獎、掉落 |
代碼示例
// 1. 基礎調用
console.log(Math.random()); // 0.2818...
console.log(Math.random()); // 0.6375...
// 2. 封裝工具函數
const Random = {
int: (min, max) => Math.floor(Math.random() * (max - min + 1)) + min,
float: (min, max) => Math.random() * (max - min) + min,
bool: (p = 0.5) => Math.random() < p,
pick: (arr) => arr[Math.floor(Math.random() * arr.length)],
shuffle: (arr) => { // Fisher-Yates
for (let i = arr.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[arr[i], arr[j]] = [arr[j], arr[i]];
}
return arr;
}
};
// 3. 使用
console.log(Random.int(1, 100)); // 1~100
console.log(Random.pick(['紅','藍','綠'])); // 隨機顏色
console.log(Random.shuffle([1,2,3,4,5])); // 打亂數組
加密級隨機數
// Web Crypto API
window.crypto.getRandomValues(new Uint32Array(1))[0] / 2**32; // [0,1) 加密安全
// 或
window.crypto.randomUUID(); // 生成 UUID v4
**安全敏感場景(Token、Nonce、密鑰)必須使用 Crypto API**,不可用 Math.random()。
copyright ©
萬盛學電腦網 all rights reserved