js 实现随机
随机数生成方法
Math.random() 方法可以生成一个介于 0(包含)和 1(不包含)之间的伪随机浮点数。这是 JavaScript 中最基本的随机数生成方式。
const randomNum = Math.random();
console.log(randomNum); // 输出类似 0.123456789
指定范围的随机整数
要生成指定范围内的随机整数,可以使用以下公式:
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min + 1)) + min;
}
随机数组元素
从数组中随机选择一个元素:
const colors = ['red', 'green', 'blue', 'yellow'];
const randomColor = colors[Math.floor(Math.random() * colors.length)];
随机字符串生成
生成指定长度的随机字符串:
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;
}
随机颜色生成
生成十六进制格式的随机颜色:
function randomHexColor() {
return `#${Math.floor(Math.random() * 16777215).toString(16).padStart(6, '0')}`;
}
随机布尔值
生成随机布尔值:
const randomBool = Math.random() >= 0.5;
随机日期
生成指定日期范围内的随机日期:
function randomDate(start, end) {
return new Date(start.getTime() + Math.random() * (end.getTime() - start.getTime()));
}
随机排列数组(洗牌算法)
使用 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;
}
加权随机选择
根据权重进行随机选择:
function weightedRandom(items, weights) {
let totalWeight = weights.reduce((a, b) => a + b, 0);
let random = Math.random() * totalWeight;
let weightSum = 0;
for (let i = 0; i < items.length; i++) {
weightSum += weights[i];
if (random <= weightSum) return items[i];
}
}
这些方法涵盖了 JavaScript 中常见的随机数应用场景,可以根据具体需求选择合适的方法或进行组合使用。






