js 实现随机
生成随机数
在JavaScript中,可以使用Math.random()生成一个0到1之间的随机浮点数(包含0,不包含1)。
const randomNum = Math.random();
console.log(randomNum); // 输出类似0.123456789
生成指定范围的随机整数
要生成一个指定范围内的随机整数,可以结合Math.floor()或Math.ceil()使用。

function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const randomInt = getRandomInt(1, 10);
console.log(randomInt); // 输出1到10之间的整数
生成随机字符串
如果需要生成随机字符串,可以使用以下方法:

function generateRandomString(length) {
const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += characters.charAt(Math.floor(Math.random() * characters.length));
}
return result;
}
const randomString = generateRandomString(10);
console.log(randomString); // 输出类似"aB3dE7fG9h"
随机打乱数组
可以使用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];
const shuffledArr = shuffleArray(arr);
console.log(shuffledArr); // 输出类似[3, 1, 5, 2, 4]
生成随机颜色
生成随机的十六进制颜色代码:
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}
const randomColor = getRandomColor();
console.log(randomColor); // 输出类似"#A1B2C3"
这些方法覆盖了常见的随机需求,可以根据具体场景选择合适的方式。






