js实现一个随机数
生成随机整数
使用Math.random()生成一个介于0(包含)和1(不包含)之间的随机小数,再通过数学运算转换为整数。例如生成1到10的随机整数:
const randomInt = Math.floor(Math.random() * 10) + 1;
Math.floor向下取整确保结果为整数,* 10将范围扩展到0-9,+ 1调整为1-10。

生成指定范围的随机整数
封装一个函数,支持自定义最小值和最大值:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 示例:生成5到15的随机数
console.log(getRandomInt(5, 15));
生成随机浮点数
类似整数方法,但保留小数部分。以下生成0到1之间的随机浮点数:

const randomFloat = Math.random();
若要指定范围(如2.5到5.5):
function getRandomFloat(min, max) {
return Math.random() * (max - min) + min;
}
console.log(getRandomFloat(2.5, 5.5));
使用Crypto API生成更安全的随机数
对于加密安全场景,可使用crypto.getRandomValues():
function secureRandomInt(max) {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return array[0] % max;
}
console.log(secureRandomInt(100)); // 0-99的随机数
注意事项
Math.random()不适合安全敏感场景,其输出可预测。- 范围计算时注意边界值,确保包含最小和最大值。
- 浮点数精度问题可能导致极小数出现,必要时用
toFixed()格式化。






