This question already has answers here:
Generate unique random numbers between 1 and 100
                            
                                (28个答案)
                            
                    
                3个月前关闭。
        

    

我必须每2秒从0-9生成3个随机数,它可以工作,但是在某些情况下,我会得到例如4 7 7的重复值。有人可以指出我的错误,太好了,谢谢

if (firstNum == secondNum || firstNum == thirdNum) {
  firstNum = Math.floor((Math.random() * 9) + 1);
} else if (secondNum == firstNum || secondNum == thirdNum) {
  secondNum = Math.floor((Math.random() * 9) + 1);
} else if (thirdNum == firstNum || thirdNum == secondNum) {
  thirdNum = Math.floor((Math.random() * 9) + 1);
}

最佳答案

把事情简单化



setInterval(function(){
  let first_number  = parseInt(Math.random()*10),
    second_number = null,
    third_number  = null;

  while (second_number == third_number || first_number == second_number || third_number == second_number){
    second_number = parseInt(Math.random()*10);
    third_number = parseInt(Math.random()*10);
  }

  console.log(first_number, second_number, third_number)
},2000)

关于javascript - 生成3个非重复值[duplicate],我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/60041315/

10-16 12:29