js实现随机
生成随机数
使用 Math.random() 方法生成一个介于 0(包含)和 1(不包含)之间的随机浮点数。
const randomNumber = Math.random();
console.log(randomNumber); // 输出类似 0.123456789
生成指定范围的随机整数
结合 Math.random() 和 Math.floor() 生成指定范围内的随机整数。例如生成 1 到 10 之间的随机整数:
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const randomInt = getRandomInt(1, 10);
console.log(randomInt); // 输出 1 到 10 之间的整数
生成随机字符串
使用 Math.random() 和 toString(36) 生成随机字符串,可以截取所需长度。
const randomString = Math.random().toString(36).substring(2, 10);
console.log(randomString); // 输出类似 "4f9d2h7k"
从数组中随机选择元素
使用 Math.random() 从数组中随机选择一个元素。
const array = ['apple', 'banana', 'orange', 'grape'];
const randomElement = array[Math.floor(Math.random() * array.length)];
console.log(randomElement); // 随机输出数组中的一个元素
生成随机颜色
生成随机的十六进制颜色代码。
function getRandomColor() {
return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`;
}
const randomColor = getRandomColor();
console.log(randomColor); // 输出类似 "#a1b2c3"
打乱数组顺序
使用 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 shuffledArray = shuffleArray([1, 2, 3, 4, 5]);
console.log(shuffledArray); // 输出类似 [3, 1, 5, 2, 4]
生成随机布尔值
生成随机的布尔值(true 或 false)。

const randomBoolean = Math.random() >= 0.5;
console.log(randomBoolean); // 随机输出 true 或 false
这些方法覆盖了常见的随机需求,可以根据具体场景选择合适的方法。






