我正在制作一个简单的脚本来创建随机数。该脚本的目的是最终将每个随机数缓存在一个数组中,然后在生成新数字时循环遍历该数组以查看前一个数字是否已被使用。如果它已被使用,那么脚本将继续循环,直到创建一个不在数组中的数字,然后返回该数字。我编写了下面的代码,逻辑很简单,但我不知道为什么它在启动时有时起作用,然后在其他时候破坏堆栈而不返回数字。
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)); /* sometimes returns a number not in the array and sometimes blows the stack. It mostly blows the stack. */
最佳答案
这是一个简单的错误。您需要传递 randomNumber
而不是 value
,因为 randomNumber
是您生成的新随机数。
checkIfInArray(randomNumb , array)
关于javascript - 检查数字是否在数组中,如果是则生成新数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27171828/