js实现随机函数
实现随机数生成
Math.random() 方法返回一个浮点数,伪随机数在范围从0到小于1,包含0但不包含1
const randomNum = Math.random();
console.log(randomNum); // 输出0到1之间的随机数
生成指定范围的随机整数
要生成一个指定范围内的随机整数,可以使用以下公式:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
这个函数会返回一个大于等于min但小于max的整数。如果需要包含max,可以修改为:
function getRandomIntInclusive(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
生成随机字符串
要生成随机字符串,可以结合随机数和字符选择:
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;
}
从数组中随机选择元素
要从数组中随机选择一个元素:
function getRandomElement(array) {
return 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;
}
使用加密安全的随机数
对于需要更高安全性的场景,可以使用crypto API:
function getSecureRandomInt(min, max) {
const range = max - min;
const randomBuffer = new Uint32Array(1);
window.crypto.getRandomValues(randomBuffer);
return min + (randomBuffer[0] % range);
}
生成随机颜色
生成十六进制格式的随机颜色:
function getRandomColor() {
const letters = '0123456789ABCDEF';
let color = '#';
for (let i = 0; i < 6; i++) {
color += letters[Math.floor(Math.random() * 16)];
}
return color;
}






