簡體   English   中英

添加到數組,檢查id是否存在並隨機更改它

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

我已經嘗試了一段時間不同的方式,我已達到這一點,無論我做什么都是錯的。

所以這就是我試過的。 首先,我創建一個隨機數並將其添加到數組中:

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問題 你究竟想在這做什么? 可能有更好的方法。

更改:

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

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