javascript - Looping through an array and look for repeating numbers -
ok, i've spent 2 days on problem , give up.
what i'm trying create array of random numbers between 0-17, each number repeat once - 36 numbers in total.
i wrote function check how many times number occurs, if it's twice, returns false.
it works until undefined number, breaks...
here's have:
var numbers = []; function checknumberrepeat(n,o,c){ var count = 0; for(var in o){ if(o[i] == n){ count ++; } } if(count == c){ return false; }else{ return n; } } function makerand(){ var rand = checknumberrepeat(math.floor(math.random()*18),numbers,2); if(rand){ return rand; }else{ makerand(); } } for(var i=0;i<36;i++){ numbers.push(makerand()); console.log(numbers); } i'm pretty sure problem happening in myrand() function
any idea?
thanks
you missing return
return makerand() it has no return returns undefined
update:
you had mistake in code. 0 falsy if (rand) when rand 0 returns false, hence 0 never inserted => endless loop
makerand shoul this:
function makerand() { var rand = checknumberrepeat(math.floor(math.random()*18),numbers,2); if (rand !== false){ return rand; } else { return makerand(); } } updated jsfiddle: http://jsfiddle.net/nayish/c9sk9suc/4/
Comments
Post a Comment