使用js实现
使用JavaScript实现
JavaScript可以通过Math.random()函数生成随机数,结合其他方法可以实现多种随机数生成需求。
// 生成0到1之间的随机小数
const randomDecimal = Math.random();
// 生成0到max之间的随机整数
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
// 生成min到max之间的随机整数
function getRandomIntInRange(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
使用Node.js实现
Node.js同样使用JavaScript的Math.random()方法,但还提供了crypto模块用于生成更安全的随机数。

// 使用Math.random()
const randomValue = Math.random();
// 使用crypto模块生成更安全的随机数
const crypto = require('crypto');
function getSecureRandomInt(max) {
return crypto.randomInt(0, max);
}
注意事项
Math.random()生成的随机数不适合安全敏感场景,如需加密安全随机数应使用Web Crypto API或Node.js的crypto模块。

随机数范围包含最小值但不包含最大值,这与许多编程语言的随机数生成器行为一致。
// 示例:生成1到10之间的随机整数
const randomNum = Math.floor(Math.random() * 10) + 1;
高级用法
可以创建可复用的随机数生成器函数,或实现特定分布的随机数生成算法。
// 可配置的随机数生成器
function createRandomGenerator(min = 0, max = 1) {
return function() {
return Math.floor(Math.random() * (max - min + 1)) + min;
};
}
// 创建1-100的随机数生成器
const generate1To100 = createRandomGenerator(1, 100);






