如何保持循环活动直到它完成,然后将其恢复为0

时间:2016-12-13 12:47:11

标签: javascript arrays json

我有一个机器人,可以检查人们何时向我发送消息。当人们发送给我时,我想要它:"!account"它检查我的json文件,如果发送消息ID的人匹配Json文件中的某人ID。如果是的话,我希望它给他发送他的"信用卡"和" steamid"到目前为止,我有点工作:

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 个答案:

答案 0 :(得分:0)

为了确保循环遍历json数组中的所有项,你的for循环应该将r的值与数组的长度进行比较 config.accounts ,或确保将值 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数组中的所有项目。