js实现随机
生成随机数
使用 Math.random() 生成一个介于 0(含)和 1(不含)之间的随机浮点数:
const randomFloat = Math.random(); // 例如 0.123456789
需要生成指定范围的随机整数时,结合 Math.floor() 或 Math.ceil():
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
const randomInt = getRandomInt(1, 10); // 生成 1-10 的整数
随机数组元素
从数组中随机选择一个元素:

const array = ['apple', 'banana', 'orange'];
const randomItem = array[Math.floor(Math.random() * array.length)];
打乱数组顺序(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;
}
shuffleArray([1, 2, 3]); // 可能返回 [2, 3, 1]
生成随机字符串
生成指定位数的随机字母数字字符串:

function randomString(length) {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let result = '';
for (let i = 0; i < length; i++) {
result += chars.charAt(Math.floor(Math.random() * chars.length));
}
return result;
}
randomString(8); // 例如 "aB3cD9fG"
密码学安全随机数
需要更高安全性时(如生成密钥),使用 crypto.getRandomValues():
const secureArray = new Uint32Array(1);
window.crypto.getRandomValues(secureArray);
console.log(secureArray[0]); // 安全的随机整数
随机颜色生成
生成十六进制随机颜色:
function randomHexColor() {
return `#${Math.floor(Math.random() * 0x1000000).toString(16).padStart(6, '0')}`;
}
randomHexColor(); // 例如 "#3a7b29"






