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 可达:
Math.floor(Math.random() * (max - min + 1)) + min
Math.floor(Math.random() * 6) + 1
Math.floor(Math.random() * (max - min)) + min
Math.random() 本身精度足够,但显示或比较时可能需要保留位数。不建议用 .toFixed() 后再参与计算(它返回字符串),推荐用乘除法四舍五入:
Math.round(Math.random() * 100) / 100
Math.round(Math.random() * Math.pow(10, n)) / Math.pow(10, n)
Math.random() 不可能返回 1,所以 Math.random().toFixed(10) 最大是 "0.9999999999"连续调用 Math.random() 不能保证不重复。真要“不重样”,得先建好池子再打乱或抽取:
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
193
立即学习“Java免费学习笔记(深入)”;
arr.sort(() => Math.random() - 0.5)(简单场景可用,非严格均匀)[...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()
u = Math.max(0.000001, u)
基本上就这些。Math.random 是起点,不是终点。用对范围、注意边界、区分类型、按需变换——随机,也可以很靠谱。
以上就是JavaScript中如何生成随机数_Math.random技巧的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号