Javascript Non-Repeating Number Generator Sometimes Returns Multiple Numbers -


i'm trying create random non-repeating number generator numbers 13. when run following function varying out puts, here results of running function 5 times using button click, , code. can't understand why it's repeating numbers.

var checkifrandom = new array();        function getrandom(){         var randomnum= math.floor(math.random()*13);         if(checkifrandom.indexof(randomnum) !== -1){             getrandom();     }else if(checkifrandom.indexof(randomnum)==-1){         checkifrandom.push(randomnum);     }          console.log(randomnum);      };  //results 2 //click 1 7, 2 //click 2 6 //click 3 1 //click 4  5,7,1 //click 5 [2, 7, 6, 1, 5]//after 5 clicks logged checkifrandom array console in chrome. 

you're using recursion, means it's storing previous, non-unique numbers in stack , still logging them. move console.log() else if reads:

function getrandom(){     var randomnum= math.floor(math.random()*13);     if(checkifrandom.indexof(randomnum) !== -1){         getrandom(); }else if(checkifrandom.indexof(randomnum)==-1){     checkifrandom.push(randomnum);     console.log(randomnum); } }; 

Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -