我有一个函数,需要用户输入才能告诉它要输出多少个随机数,以及要在其之间进行随机数的范围(例如1-90)。问题在于它将给出重复的数字,但是我只需要唯一的数字。有谁知道我该如何更改代码来实现这一目标?
function random() {
let randomNums = [];
// Get how many random numbers to output
let numBox = document.querySelector('.numBox').value;
// Get the highest number range should go to (ex. 1-70)
let highestNumber = document.querySelector('.highestNumber').value;
// Loop to generate random numbers and push to randomNums array
for (let i = 0; i < numBox; i++) {
let num = Math.floor(Math.random() * highestNumber) + 1;
randomNums.push(` ${num}`)
}
// Sort numbers from lowest to highest
randomNums.sort(function(a, b) {return a - b;});
// Output numbers
document.querySelector('.randomOutput').innerHTML = randomNums;
}
只需将您的循环更改为while循环,并检查数组是否尚未具有该值:
let i = 0;
while(i < numBox) {
let num = Math.floor(Math.random() * highestNumber) + 1;
if (randomNums.indexOf(num) == -1) {
randomNums.push(num);
i++;
}
}
您可以简单地生成并验证它是否存在,直到获得必要的随机唯一数字为止>
while (randomNums.length < numBox) {
let num = Math.floor(Math.random() * highestNumber) + 1;
if (randomNums.indexOf(num) === -1) randomNums.push(num);
}
这里是避免while()
循环的方法。
这是修复它的代码,如果其他人有类似的问题:
如@CodeManiac所述,在@BilalSiddiqui解决方案中使用“设置”。