欢迎来到我的博客文章!所有文章都是满满的前端干货,文章简明扼要。
<script>
// ❌ 不能保证不重复
let arr = Array.from({length:5}, () => Math.floor(Math.random()*31) + 2)
</script> 问题:这种方法生成5个随机数,但无法保证它们不重复。
使用 Set 数据结构自动去重,简洁高效。
<script>
function getRandomUniqueArray(count, min = 2, max = 32) {
const set = new Set();
while (set.size < count) {
const num = Math.floor(Math.random() * (max - min + 1)) + min;
set.add(num);
}
return Array.from(set); // 或 [...set]
}
const arr = getRandomUniqueArray(5);
console.log(arr);
</script> ✅ 优点:
使用递归算法实现不重复的随机数数组。
<script>
let arr = [];
let random;
function getRandom() {
random = Math.floor(Math.random() * 31) + 2; // ✅ [2, 32]
if (arr.indexOf(random) === -1) {
arr.push(random);
}
if (arr.length < 5) {
getRandom();
}
}
getRandom();
console.log(arr);
</script> ✅ 递归方案特点:
Set 方案优势:
递归方案优势:
// 生成 [min, max] 范围的随机整数 Math.floor(Math.random() * (max - min + 1)) + min // 示例:[2, 32] Math.floor(Math.random() * 31) + 2
const set = new Set(); set.add(1); set.add(2); set.add(1); // 重复值不会被添加 console.log(set.size); // 2 // 转换为数组 const arr = Array.from(set); // 或 [...set]
function getRandom() {
// ... 处理逻辑
if (arr.length < 5) {
getRandom(); // 递归调用
}
// arr.length === 5 时自动停止
} 注意事项: