2016-12-13 39 views
0

我有檢查,當人們給我一個信息一個機器人。我想它所以當人們給我:「賬戶」,它會檢查通過的json文件,如果這個傢伙發送消息的ID,匹配在JSON文件中某人的ID。如果是的話,我希望它把他送到他的「信用」和「steamid」到目前爲止,我已經得到了它種工作:如何保持對循環有效,直到它完成,然後把它回0

ok = 1; 
if(ok == 1) { 
    console.log("[SERVER] "+steamID.getSteamID64()+" is asking for his account information."); 
    for(r=0;r<config.tradesettings.amountofaccounts+1;r+=1) { 
     if(config.accounts[r].steamID == steamID.getSteamID64()) { 
      ok = 0; 
      console.log("[SERVER] "+ steamID.getSteamID64() +" is asking for his account info, respondig with it.\n") 
      client.chatMessage(steamID.getSteamID64(), "\nDisplaying your account on this bot\nBotID: "+config.accounts[r].botID+"\nSteamID: "+config.accounts[r].steamID+"\nBalance: "+config.accounts[r].balance); 

      console.log(r); 
      return; 
     } else { 
      //do nothing 
     } 
    } 
} 

現在正在工作,但它不是通過所有的檢查JSON文件。 for循環只激活一次,所以它只檢查第一個或第二個json。 我將如何使for循環活動,直到它完成搜索,然後設置r = 0

這裏是json文件被稱爲config.json,在這裏它是。

"accounts":[ 
    { 
    "botID":"0", 
    "steamID":"2919", 
    "balance": 54 
    }, 
    { 
    "botID":"1", 
    "steamID":"", 
    "balance": 0 
    }, 
    { 
    "botID":"2", 
    "steamID":"", 
    "balance": 0 
    }, 
    { 
    "botID":"3", 
    "steamID":"76561198026027024", 
    "balance": 0 
    } 
] 
+1

如果你想有一個循環,一個函數裏面,每一個元素處理在一個數組,你不'return' - 即退出函數(你沒有顯示) –

+0

裏面的for循環使用「繼續」保持循環或「休息」來停止循環。那個回報就是搞砸了。 – yBrodsky

+0

謝謝作品!謝謝! –

回答

0

要確保遍歷JSON數組中的所有項目,運行你的for循環應該與陣列config.accounts的長度比較r的值,或確保該值config.tradesettings.amountofaccounts被設置於所述陣列的長度。

下面的代碼替換for循環應該通過迭代所有的數組項。

for(r = 0; r < config.accounts.length - 1; r++) { 
     if(config.accounts[r].steamID == steamID.getSteamID64()) { 
      ok = 0; 
      console.log("[SERVER] "+ steamID.getSteamID64() +" is asking for his account info, respondig with it.\n") 
      client.chatMessage(steamID.getSteamID64(), "\nDisplaying your account on this bot\nBotID: "+config.accounts[r].botID+"\nSteamID: "+config.accounts[r].steamID+"\nBalance: "+config.accounts[r].balance); 

      console.log(r); 
      break; 
     } 
    } 

    return; 

這應該遍歷json數組中的所有項目。

相關問題