Math.random() 生成 [0,1) 浮点数,需配合 Math.floor 等取整;无原生随机整数方法;非密码学安全;不可设种子;安全场景须用 crypto API。

Math.random() 生成的是 [0, 1) 区间的浮点数,不是整数
很多人一上来就写 Math.random() * 10 然后直接用,结果发现偶尔得到 10 —— 其实不会,因为 Math.random() 永远返回小于 1 的数,所以 Math.random() * 10 结果是 [0, 10),最大接近但不等于 10。如果要取整到 [0, 9],得用 Math.floor();要 [1, 10],就得 Math.floor(Math.random() * 10) + 1。
常见错误现象:
- 写 Math.round(Math.random() * 10) → 导致 0 和 10 出现概率只有其他数的一半(因为四舍五入边界压缩)
- 忘记加 1 就想从 1 开始 → 得到 [0, n) 而非 [1, n]
- 通用整数随机公式(含边界):
Math.floor(Math.random() * (max - min + 1)) + min - 生成 1~6 的骰子数:
Math.floor(Math.random() * 6) + 1 - 生成 0~255 的颜色分量:
Math.floor(Math.random() * 256)
Math 对象没有内置“随机整数”方法,别找 Math.randomInt() 这种不存在的函数
Math.random() 是唯一原生随机数生成入口,Math.randomInt()、Math.rand()、Math.randint() 全都不存在 —— 浏览器和 Node.js 当前标准里都没有。ECMAScript 提案曾讨论过 Math.randomInt(min, max),但截至 2024 年仍未落地,不能在生产环境依赖。
如果你看到别人用了 Math.randomInt(),大概率是:
- 用了 Polyfill 或自定义扩展(污染了 Math 原型,不推荐)
- 框架或库封装的工具函数(比如 Lodash 的 _.random()),不是原生 Math
- 安全做法:自己封装一个可复用的函数,比如:
function randomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
} - 注意参数顺序:
min必须 ≤max,否则结果不可控 - 不建议修改
Math.prototype,会影响全局和他人代码
Math.random() 不适合密码学场景,安全随机请用 crypto.getRandomValues()
Math.random() 是伪随机、可预测、无熵源,仅适用于 UI 动画、抽样展示、游戏逻辑等非敏感用途。若用于生成 token、密码、加密盐值,会直接导致安全漏洞。
替代方案:
- 浏览器中用 crypto.getRandomValues()(注意是小写的 crypto,不是 Crypto)
- Node.js 中用 crypto.randomBytes() 或 crypto.webcrypto.getRandomValues()(v19+)
- 生成一个安全的 0~255 整数:
const arr = new Uint8Array(1);
crypto.getRandomValues(arr);
const secureRandom = arr[0]; - 生成安全的 6 位数字验证码:
const arr = new Uint8Array(3);
crypto.getRandomValues(arr);
const code = (arr[0] * 256 * 256 + arr[1] * 256 + arr[2]) % 1000000; - 不要试图用
Math.random()“多次叠加”来“增强随机性”——没用,仍不安全
重复调用 Math.random() 不会自动更新种子,也不需要手动 seed
Math.random() 的实现由 JS 引擎控制(V8、SpiderMonkey 等),开发者无法设置 seed,也无法重置。所谓“设置随机种子”的需求,在标准 JS 中无解 —— 这意味着你无法在测试中稳定复现某次随机序列。
立即学习“Java免费学习笔记(深入)”;
如果你需要可重现的随机行为(比如单元测试、游戏存档同步):
- 必须引入第三方确定性 PRNG 库,如 seedrandom
- 或自己实现简单线性同余生成器(LCG),用固定 seed 初始化
- 用
seedrandom示例:const seedrandom = require('seedrandom');
const rng = seedrandom('my-seed');
console.log(rng()); // 每次运行都一样 -
Math.random()的输出分布质量因引擎而异,但对一般用途足够;不要为“不够随机”过度优化 - 也不要尝试用时间戳、
Math.random()自身输出做 seed —— 既不增加安全性,也不提升可重现性
真正麻烦的从来不是“怎么生成一个随机数”,而是搞清它是否够随机、是否可重现、是否够安全 —— 这三个问题的答案,全在你调用的那行代码之前。











