javascript - 添加到数组中,检查id是否存在并随机更改

标签 javascript arrays

有一段时间我一直在尝试不同的方法,但我已经到了无论我做什么都会出错的地步。

这就是我尝试做的事情。首先,我创建一个随机数并将其添加到数组中:

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/

相关文章:

javascript - 从不同按钮调用的独特弹出窗口 - ExtJS

javascript - Action 与 Javascript 链接并将值传递给 Controller

JavaScript ES6 : Split array into rest and last with destructuring

arrays - 给定两个数组 A 和 Q,对于 Q 的每个元素,找到 A 中差异最小的元素

javascript - jquery验证: how to validate user name minlength differently for Chinese and English characters?

javascript - jQuery - 在新选项卡表单中打开链接提交

javascript - 比较对象之间的属性子集

java - 数组不会通过 for 循环到达下一个位置

C `Abort trap: 6` 仅在某些条件下

PHP:在数组中分隔 1 个键的 2 个或多个值