gpt4 book ai didi

javascript - 生成 3 个非重复值

转载 作者:行者123 更新时间:2023-12-02 21:54:32 24 4
gpt4 key购买 nike

我必须每 2 秒生成 3 个 0-9 的随机数,它可以工作,但是在某些情况下我会得到重复的值,例如 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 个非重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60041315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com