js实现随机函数
生成随机数
在JavaScript中,Math.random() 是最基础的随机数生成方法,返回一个介于0(包含)和1(不包含)之间的浮点数。
const randomNum = Math.random();
console.log(randomNum); // 输出类似 0.123456789
生成指定范围的随机整数
结合 Math.floor() 或 Math.ceil() 可以生成指定范围内的随机整数。以下是一个生成 min 到 max 之间随机整数的函数:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
console.log(getRandomInt(1, 10)); // 输出 1 到 10 之间的整数
生成随机字符串
如果需要生成随机字符串(如用于ID或验证码),可以通过以下方式实现:
function generateRandomString(length) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
console.log(generateRandomString(8)); // 输出类似 "aB3dE7fG"
随机打乱数组
使用 Fisher-Yates 洗牌算法可以高效地随机打乱数组:
function shuffleArray(array) {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array;
}
const arr = [1, 2, 3, 4, 5];
console.log(shuffleArray(arr)); // 输出类似 [3, 1, 5, 2, 4]
生成不重复的随机数
如果需要从一组数据中随机选取不重复的多个值,可以使用以下方法:
function getUniqueRandomItems(array, count) {
const shuffled = [...array].sort(() => 0.5 - Math.random());
return shuffled.slice(0, count);
}
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
console.log(getUniqueRandomItems(numbers, 3)); // 输出3个不重复的随机数
使用 crypto.getRandomValues 生成更安全的随机数
如果需要更高安全性的随机数(如加密场景),可以使用 crypto.getRandomValues:

function getSecureRandomInt(min, max) {
const range = max - min + 1;
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer);
return min + (randomBuffer[0] % range);
}
console.log(getSecureRandomInt(1, 100)); // 输出1到100之间的安全随机整数






