js实现随机
生成随机数
在JavaScript中,可以使用Math.random()方法生成一个介于0(包含)和1(不包含)之间的伪随机浮点数。以下是基本用法:
const randomNumber = Math.random();
console.log(randomNumber); // 输出类似 0.123456789
生成指定范围的随机整数
如果需要生成指定范围内的随机整数,可以结合Math.floor()或Math.ceil()方法:
// 生成0到9之间的随机整数
const randomInt = Math.floor(Math.random() * 10);
console.log(randomInt);
// 生成1到10之间的随机整数
const randomIntInRange = Math.floor(Math.random() * 10) + 1;
console.log(randomIntInRange);
生成更通用的随机数函数
可以封装一个函数来生成任意范围内的随机整数:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// 生成5到15之间的随机整数
console.log(getRandomInt(5, 15));
生成随机字符串
如果需要生成随机字符串,可以结合Math.random()和字符串操作:
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;
}
console.log(generateRandomString(10)); // 输出类似 "aB3dE7fG9h"
使用Crypto API生成更安全的随机数
对于需要更高安全性的场景,可以使用crypto.getRandomValues()方法:
function getSecureRandomInt(min, max) {
const array = new Uint32Array(1);
window.crypto.getRandomValues(array);
return min + (array[0] % (max - min + 1));
}
console.log(getSecureRandomInt(1, 100));
随机数组元素
从数组中随机选择一个元素:
const colors = ['red', 'green', 'blue', 'yellow'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
console.log(randomColor);
打乱数组顺序
使用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 numbers = [1, 2, 3, 4, 5];
console.log(shuffleArray(numbers));






