Reputation: 119
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();
Upvotes: 0
Views: 51
Reputation: 13896
Use indexOf
to check if the array has the value before pushing:
if (allAnswers.indexOf(wrongAnswers) === -1) {
allAnswers.push(wrongAnswers);
}
Upvotes: 1