If condition not met execute function again - causing js error
I have the following function
function randomNum(max, used){
newNum = Math.floor(Math.random() * max + 1);
if($.inArray(newNum, used) === -1){
console.log(newNum + " is not in array");
return newNum;
}else{
return randomNum(max,used);
}
}
Basically I am creating a random number between 1 - 10 and checking to see
if that number has already been created, by adding it to an array and
checking the new created number against it. I call it by adding it to a
variable..
UPDATED:
for(var i=0;i < 10;i++){
randNum = randomNum(10, usedNums);
usedNums.push(randNum);
//do something with ranNum
}
This works, but in Chrome I get the following error:
Uncaught RangeError: Maximum call stack size exceeded
Which I guess it's because I am calling the function inside itself too
many times. Which means my code is no good.
Can someone help me with the logic? what's a best way to make sure my
numbers are not repeating?
No comments:
Post a Comment