【发布时间】:2021-10-17 05:37:43
【问题描述】:
一个初学者的问题。 所以我用过
let myArray = [];
function randomNumbers(){
for(let i = 0; i < 3; i++){
if(Math.floor(Math.random()*10) !== myArray[i]){
myArray.push(Math.floor(Math.random()*10));
}
}
}
randomNumbers()
console.log(myArray)
上面的代码按预期给了我 3 个随机数,但有时它给了我两次相同的数字,在极少数情况下,同样的数字 3 次。
【问题讨论】:
-
您可以使用数字 0 到 9 创建数组,然后打乱该数组,并从该数组中获取前 3 个数字
标签: javascript arrays random numbers unique