提问者:小点点

node.js For()循环未按预期工作


首先我要说的是,我对编程的世界还是很新鲜的。

else if (message.content.startsWith('s!stats defense')){
        const args1 = message.content.slice(16).split();
        const command1 = args1.shift().toLowerCase();
        editedmessage = command1 
        var i = 0;
        for (i = 0; i != 0;){
            let _name = client.defense[editedmessage].Name
            if (error){
                message.channel.send('Player is not in the defensive stats database. If you think it should be DM Toasty')
                i = -1
            } else {
                message.channel.send(_name)
                i = 1
            }
           
            
        }
        message.channel.send(_name)

它直接跳过for()循环。JSON文件是:

{
    "aaron ozark": {
      "Name": "Aaron Ozark",
      "Games": 1,
      "Tackles": 1,
      "Sacks": 0,
      "Passesdefended": 0,
      "Interceptions": 0,
      "ForcedFumbled": 0,
      "FumblesRecovered": 0,
      "Touchdowns": 0,
      "Team": "Vipers",
      "position": "WR",
      "FantasyPoints": 0
    },
    "adelie de pengu": {
      "Name": "Adelie De Pengu",
      "Games": 7,
      "Tackles": 27,
      "Sacks": 1,
      "Passesdefended": 3,
      "Interceptions": 2,
      "ForcedFumbled": 0,
      "FumblesRecovered": 0,
      "Touchdowns": 0,
      "Team": "Wallabies",
      "position": "DB",
      "FantasyPoints": 6.5
    },
    "akashi seijuro": {
      "Name": "Akashi Seijuro",
      "Games": 7,
      "Tackles": 24,
      "Sacks": 1,
      "Passesdefended": 2,
      "Interceptions": 3,
      "ForcedFumbled": 0,
      "FumblesRecovered": 1,
      "Touchdowns": 0,
      "Team": "Aztecs",
      "position": "DB",
      "FantasyPoints": 10
    }
}

稍后将在代码中使用i变量来确定其余的统计是否存在。我知道我做错了什么,因为当我在for()循环之外添加最后一个message.channel.send(_name)时,if提醒我“_name未定义”。


共2个答案

匿名用户

您的for循环不正确。目前您有

for (i = 0; i != 0;)

您正在将i设置为0,循环的退出条件是i!=0,因此循环不会发生,因为最初的退出条件是false

我建议阅读for循环的工作原理:MDN文档

另外,我不明白为什么你需要一个循环,因为你并不是真的在循环任何东西。

没有定义_name是因为您在for循环块中定义了_name

for (...) {
  let _name
}

message.channel.send(_name)

_name需要位于for循环块之外。

let _name

for (...) {
  _name = ...
}

message.channel.send(_name)

总体而言,我发现在您的UseCase的实现中存在很多问题。我建议您后退一步,重新考虑您的代码。

匿名用户

for循环只要第二条语句为真就会执行(它在每次循环执行之前都会检查。所以

for (...; false; ...)

根本不执行并且

for (...; true; ...)

无限执行。