Skip to content
Advertisement

How to choose randomly unique number when the button is clicked

I am trying to choose random unique numbers everytime when I click button. For this my function is:

JavaScript

But the problem is if the random number is already on my list, I need to click the button again to generate new number and it goes until it find the number which is not on the list. But I want to generate number which is not on the list directly so I dont need to click the button everytime. Thanks for you helps.

Advertisement

Answer

You are in a right track, except the while loop should be for random number generator, not pushing number into an array:

JavaScript
JavaScript

Note, that this might eventually lead to a freeze, since there is no fail safe check if array is full, so to battle that we should also check length of the array:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement