萬盛學電腦網

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

JavaScript Math.random() 方法詳解:生成偽隨機數與常用範圍映射技巧

基本特性

Math.random() // 返回 [0, 1) 偽隨機浮點數(含 0,不含 1)
  • **偽隨機**:確定性算法(如 xorshift128+),種子不可設置,不可用於加密。
  • **均勻分佈**:長期統計近似均勻。
  • **無參數**:調用無需傳參。

常用範圍映射公式

代碼示例

// 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
需求公式示例
[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隨機真假
加權隨機累積權重數組 + 二分查找抽獎、掉落