samedi 14 août 2021

How can I generate 3 different (unique) numbers in javascript? [duplicate]

a question from a beginner. So I've used

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)

Code above gives me 3 random number as intended but sometimes it's giving me same number twice and in very rare occasion, same number 3 times.




Aucun commentaire:

Enregistrer un commentaire