如何获得一定范围内的一定数量的唯一随机数?

问题描述 投票:0回答:5

我有一个函数,需要用户输入才能告诉它要输出多少个随机数,以及要在其之间进行随机数的范围(例如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;
}
javascript random numbers shuffle
5个回答
1
投票

只需将您的循环更改为while循环,并检查数组是否尚未具有该值:

let i = 0;
while(i < numBox) {
    let num = Math.floor(Math.random() * highestNumber) + 1;
    if (randomNums.indexOf(num) == -1) {
        randomNums.push(num);
        i++;
    }
}

0
投票

您可以简单地生成并验证它是否存在,直到获得必要的随机唯一数字为止>

while (randomNums.length < numBox) {
    let num = Math.floor(Math.random() * highestNumber) + 1;
    if (randomNums.indexOf(num) === -1) randomNums.push(num);
}

0
投票

这里是避免while()循环的方法。


0
投票

这是修复它的代码,如果其他人有类似的问题:


0
投票

如@CodeManiac所述,在@BilalSiddiqui解决方案中使用“设置”。

© www.soinside.com 2019 - 2024. All rights reserved.