javascript - Check if number is in an array an generate new number if it is -
i'm making simple script create random number. intent of script cache each random number in array , loop through array when generating new numbers see if previous 1 had been used. if has been used script continue looping until number created not in array, , return that number. wrote code below , logic simple enough don't know why works when launched sometimes , blows stack @ other times without returning number.
var oldnumbs = [1,2,3,4,6,7] // dummy data var randomnumb = math.floor((math.random() * 10) +1); function checkifinarray(value, array) { if(array.indexof(value) > -1){ randomnumb = math.floor((math.random() * 10) +1); checkifinarray(value, array) } else{ return randomnumb } } console.log(checkifinarray(randomnumb,oldnumbs)); /* returns number not in array , blows stack. blows stack. */
simple mistake is. need pass randomnumb
instead of value
since randomnumb
new random number generated.
checkifinarray(randomnumb , array)
Comments
Post a Comment