简体   繁体   English

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

[英]Add to array, check if id exists and randomly change it

I've been trying different ways for a while and I've reached that point where whatever I do just gets wrong. 我已经尝试了一段时间不同的方式,我已达到这一点,无论我做什么都是错的。

So this is what I've tried to do. 所以这就是我试过的。 First I create a random number and add it to an array: 首先,我创建一个随机数并将其添加到数组中:

for(.......){
  random[i] = Math.floor(Math.random() * (word.length));

Then another random number is added to the array: 然后将另一个随机数添加到数组中:

randomkey[i] = Math.floor(Math.random() * (word.length));

Then I create this function: 然后我创建了这个函数:

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;
}

Now, the problem is that it won't return the new value when the random number already exists. 现在,问题是当随机数已经存在时它不会返回新值。

Since you're iterating through the whole list, there will always be a point where word[i] == word[random] (because you've comparing the word to itself.) A quick fix would be: 因为你在整个列表中进行迭代,所以总会有一个word[i] == word[random] (因为你将这个单词与自身进行比较)。快速解决方法是:

for(var i=0;i<randomkey.length+1; i++){
    if(word[i] == word[random] && i !== random) {
        accept = false;
        break;
    }
}

You'll also need to return your recursive call: 您还需要返回递归调用:

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);
}

Honestly, I think you've run into the XY problem . 老实说,我认为你遇到了XY问题 What exactly are you trying to do here? 你究竟想在这做什么? There's probably a better way. 可能有更好的方法。

Change: 更改:

for(.......){
  random[i] = Math.floor(Math.random() * (word.length));
// You're assigning a random number to random[i]

to

for(.......){
  random[i] = words[Math.floor(Math.random() * (word.length))];
// Whereas you should be assigning words[random number] to random[i]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM