<ol><li>生成0到1之间的浮点数直接使用math.random();2. 生成0到max(不包含)的整数使用math.floor(math.random() max);3. 生成min到max之间包含边界的整数应使用math.floor(math.random() (max - min + 1)) + min,注意+1避免范围缺失;4. 安全敏感场景需用window.crypto.getrandomvalues()获取加密安全随机数,不可使用math.random();5. 避免使用math.round()导致分布偏斜,应使用math.floor()保证均匀分布;6. math.random()不可播种,如需可重现序列应引入第三方prng库;7. 注意浮点数精度限制和crypto api性能开销,在非安全场景优先使用math.random()以提升性能。上述实践覆盖了javascript中随机数生成的核心方法与常见陷阱,完整且准确地提供了从基础使用到高级注意事项的解决方案。</li></ol>

在JavaScript里,生成随机数主要依靠
Math.random()
Math.floor()

Math.random()
0.123456789...
生成0到1之间的浮点数:

const randomFloat = Math.random(); console.log(randomFloat); // 比如:0.78912345
生成指定范围内的整数(包含最小值,不包含最大值):
如果你想得到一个0到
max
max

// 生成0到9之间的整数(0-9) const maxExclusive = 10; const randomNumber = Math.floor(Math.random() * maxExclusive); console.log(randomNumber); // 比如:5
这里,
Math.random() * maxExclusive
maxExclusive
maxExclusive
Math.floor()
生成指定范围内的整数(包含最小值和最大值):
这可能是最常见的需求了,比如生成一个1到100之间的随机整数。这个公式稍微复杂一点,但非常实用:
// 生成1到100之间的整数(包含1和100)
function getRandomIntInclusive(min, max) {
min = Math.ceil(min); // 确保最小值是整数
max = Math.floor(max); // 确保最大值是整数
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const minInclusive = 1;
const maxInclusive = 100;
const randomNumberInRange = getRandomIntInclusive(minInclusive, maxInclusive);
console.log(randomNumberInRange); // 比如:73这里的逻辑是:
max - min + 1
Math.random()
Math.floor()
min
min
max
在我看来,生成特定范围内的整数,尤其是包含两端边界的,那个
Math.floor(Math.random() * (max - min + 1)) + min
+1
max
一个好的实践是把它封装成一个可复用的函数,就像上面
getRandomIntInclusive
min
max
另外,关于
Math.random()
Math.random()
当涉及到安全敏感的场景,比如生成会话ID、密码重置令牌、或者任何需要抵抗预测攻击的随机数据时,
Math.random()
Web Cryptography API
window.crypto.getRandomValues()
这个API与
Math.random()
使用
getRandomValues
// 生成一个16字节(128位)的加密安全随机数
function generateSecureRandomBytes(length) {
const array = new Uint8Array(length); // 创建一个无符号8位整数数组
window.crypto.getRandomValues(array); // 用加密安全的随机数填充它
return array;
}
const secureBytes = generateSecureRandomBytes(16);
console.log(secureBytes); // 比如:Uint8Array [123, 45, 201, ...]
// 如果你需要一个加密安全的随机ID字符串,可以这样转换
function generateSecureRandomHex(length) {
const bytes = generateSecureRandomBytes(length);
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
}
const secureId = generateSecureRandomHex(16); // 生成一个32字符的十六进制随机ID
console.log(secureId); // 比如:a3f4e1c2d0b9a8f7e6d5c4b3a2f1e0d9这里需要注意的是,
window.crypto.getRandomValues()
crypto
crypto.randomBytes()
除了前面提到的
+1
一个常见的“陷阱”是偏斜(Bias)。比如,有些人可能会尝试用
Math.round(Math.random() * max)
Math.round()
max
Math.floor()
另一个问题是种子(Seed)。
Math.random()
还有就是浮点数精度。虽然
Math.random()
最后,就是性能考量。
Math.random()
window.crypto.getRandomValues()
Math.random()
Math.random()
以上就是js中如何生成随机数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号