萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 產生任意範圍隨機整數:Math.random() 進階應用

基礎公式

`Math.random()` 回傳 `[0, 1)` 區間浮點數。要獲得 `[min, max]` 區間**整數**:

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

推導過程

  1. `Math.random()` → `[0, 1)`
  2. `* (max - min + 1)` → `[0, max - min + 1)`
  3. `Math.floor()` → `[0, max - min]` 整數
  4. `+ min` → `[min, max]` 整數

驗證範例

// 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

進階變體

1. 隨機浮點數 [min, max)

function randomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

2. 從陣列隨機取元素

function randomChoice(arr) {
  return arr[Math.floor(Math.random() * arr.length)];
}
var colors = ['red', 'green', 'blue'];
console.log(randomChoice(colors)); // 隨機顏色

3. 加權隨機 (權重陣列)

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]);

4. 密碼學安全隨機 (Crypto API)

// 適用於 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()`。

copyright © 萬盛學電腦網 all rights reserved