简体   繁体   中英

Generate a random number 4 times no repeating Javascript?

I am wanting to generate a random number between 1-100, but I am only wanting to generate those numbers once each time. I have a loop that runs 3 times to run the .Math and then push that into an array. But I dont want the situation where it generates the same number more than once.

I have put 21 in the allAnswers[] array as that is something that will stay consistent. Is there a way to generate and then check that array if that number exists and then run the .math again?

 function buttonGenerator(){ var allAnswers = [21], randomizer = []; // Generates 3 random answers for(a = 0 ; a < 3; a++) { wrongAnswers = Math.floor((Math.random() * 100) + 1); allAnswers.push(wrongAnswers); } // Generates random buttons while inputting the correct and incorrect answers randomly for(i = 0 ; i < 4; i++) { var buttonArea = $("#answerOptions"); input = $('<button class="col-xs-6 btn btn-primary"></button>'); input.appendTo(buttonArea); } shuffle(allAnswers); console.log(allAnswers); } buttonGenerator(); 

Use indexOf to check if the array has the value before pushing:

if (allAnswers.indexOf(wrongAnswers) === -1) {
  allAnswers.push(wrongAnswers);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM