有一段时间我一直在尝试不同的方法,但我已经到了无论我做什么都会出错的地步。
这就是我尝试做的事情。首先,我创建一个随机数并将其添加到数组中:
for(.......){
random[i] = Math.floor(Math.random() * (word.length));
然后另一个随机数被添加到数组中:
randomkey[i] = Math.floor(Math.random() * (word.length));
然后我创建这个函数:
var accept=true;
// word is a text (length:22)
function acceptRandom(random,word){
stop:
for(var i=0;i<randomkey.length+1; i++){
if(word[i] != word[random])
accept = true;
else {
accept = false;
break stop;
}
}
if(accept == false){
newrandom = Math.floor(Math.random() * (word.length));
// Random number exists so we call the function again with a new value
acceptRandom(newrandom,word);
} else
return random;
}
现在的问题是,当随机数已经存在时,它不会返回新值。
最佳答案
由于您要遍历整个列表,因此总是会存在一个点,其中word[i] == word[random]
(因为您比较了一个快速的解决方法是:
for(var i=0;i<randomkey.length+1; i++){
if(word[i] == word[random] && i !== random) {
accept = false;
break;
}
}
您还需要返回递归调用:
if(accept == false){
newrandom = Math.floor(Math.random() * (word.length));
// Random number exists so we call the function again with a new value
return acceptRandom(newrandom,word);
}
老实说,我认为您已经遇到了 XY problem 。你到底想在这里做什么?可能有更好的方法。
关于javascript - 添加到数组中,检查id是否存在并随机更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13437071/