JavaScript中生成随机数最常用Math.random(),但需正确处理范围、精度、去重和分布:闭区间整数用Math.floor(Math.random()(max-min+1))+min;保留n位小数用Math.round(Math.random()10n)/10n;去重推荐洗牌或Set;正态分布可用Box-Muller变换。

JavaScript 中生成随机数最常用的方法是 Math.random(),但它默认只返回 [0, 1) 区间的浮点数。想得到整数、指定范围、唯一值或满足特定分布,需要配合其他操作。关键不是“用不用 Math.random”,而是“怎么用对”。
生成指定范围的整数(含上下界)
很多人写错成 Math.floor(Math.random() * (max - min)) + min,结果 max 永远取不到。正确写法要确保 max 可达:
- 生成 [min, max] 闭区间整数:
Math.floor(Math.random() * (max - min + 1)) + min - 例子:随机 1~6(模拟骰子)→
Math.floor(Math.random() * 6) + 1 - 若需 [min, max),则去掉 +1:
Math.floor(Math.random() * (max - min)) + min
生成随机小数并控制精度
Math.random() 本身精度足够,但显示或比较时可能需要保留位数。不建议用 .toFixed() 后再参与计算(它返回字符串),推荐用乘除法四舍五入:
- 保留 2 位小数(数值类型):
Math.round(Math.random() * 100) / 100 - 更通用:保留 n 位 →
Math.round(Math.random() * Math.pow(10, n)) / Math.pow(10, n) - 注意:
Math.random()不可能返回 1,所以Math.random().toFixed(10)最大是 "0.9999999999"
避免重复的简单随机序列(如抽签)
连续调用 Math.random() 不能保证不重复。真要“不重样”,得先建好池子再打乱或抽取:
立即学习“Java免费学习笔记(深入)”;
- 打乱数组(Fisher–Yates 洗牌):
arr.sort(() => Math.random() - 0.5)(简单场景可用,非严格均匀) - 更可靠方式:手动实现洗牌,或用 Set 缓存已用值,循环生成直到不重复
- 例子:从 1~10 随机取 3 个不重复数:
[...new Set(Array.from({length: 10}, (_, i) => i + 1).map(() => Math.ceil(Math.random() * 10)))].slice(0, 3)(适合小规模)
生成正态分布等非均匀随机数(进阶)
Math.random() 天然均匀分布。如需近似正态(高斯)分布,可用 Box-Muller 变换:
- 基础版(标准正态):
const randGauss = () => { const u = 1 - Math.random(); const v = Math.random(); return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v); }; - 调整均值 μ 和标准差 σ:
μ + σ * randGauss() - 注意:此方法有性能开销,且极小概率出现 NaN(log(0)),实际中可加兜底
u = Math.max(0.000001, u)
基本上就这些。Math.random 是起点,不是终点。用对范围、注意边界、区分类型、按需变换——随机,也可以很靠谱。










