Math.random()生成[0,1)浮点数,需运算转换:整数用Math.floor(Math.random()(max-min+1))+min;小数用Math.round(Math.random()10^n)/10^n;取元素用arr[Math.floor(Math.random()*arr.length)];打乱用Fisher-Yates算法;禁用sort随机排序及安全场景。

JavaScript中Math.random()本身只生成[0, 1)区间内的浮点数,真正实用的随机数需要配合运算调整范围和类型。掌握几个关键转换逻辑,就能准确生成整数、指定范围、去重数组或随机打乱等常见需求。
生成指定范围的整数(含上下界)
很多人误以为Math.random() * (max - min)就能得到[min, max]的整数,其实它默认不含max,且容易忽略向下取整的边界问题。正确做法是:先扩大范围,再用Math.floor向下取整(确保包含min),同时让上限+1来覆盖max。
- 生成[min, max]之间的随机整数:
Math.floor(Math.random() * (max - min + 1)) + min - 例如生成1–10的整数:
Math.floor(Math.random() * 10) + 1 - 生成0–99的整数:
Math.floor(Math.random() * 100)
生成小数并控制精度
直接使用Math.random()得到的是最多17位小数的浮点数,但业务中常需保留固定位数(如价格、百分比)。不建议用toFixed()后转回数字(会变字符串),更稳妥的是用乘-四舍五入-除的组合。
- 生成保留2位小数的0–100之间随机数:
Math.round(Math.random() * 10000) / 100 - 通用公式(n位小数):
Math.round(Math.random() * Math.pow(10, n)) / Math.pow(10, n) - 注意:
Math.round是四舍五入,若需始终向下(如模拟flooring折扣),改用Math.floor
从数组中随机取元素或打乱顺序
单独调用Math.random()只能得索引,结合length即可抽样;打乱则推荐Fisher-Yates算法——高效、均匀、原地修改,比多次sort(() => Math.random() - 0.5)更可靠(后者分布不均)。
立即学习“Java免费学习笔记(深入)”;
- 随机取一个元素:
arr[Math.floor(Math.random() * arr.length)] - Fisher-Yates 打乱数组:
function shuffle(arr) { 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; }
避免常见陷阱
几个看似简单却高频出错的点:
-
不要用
Math.random() - 0.5做排序依据:ECMAScript规范不保证比较函数返回值为负/零/正时的排序稳定性,结果不可预测 -
重复调用不等于“更随机”:连续多次
Math.random()不会提升随机性,反而可能因执行过快导致时间戳相近(在极少数弱伪随机实现中) -
服务端或安全场景慎用:
Math.random()是确定性伪随机,不可用于密码、token、抽奖核心逻辑,应改用crypto.getRandomValues()









