【问题标题】:Node.js For() loop not working as expectedNode.js For() 循环未按预期工作
【发布时间】:2020-10-03 14:37:06
【问题描述】:

我将首先声明我对编程世界非常陌生。

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) 时,如果提醒我“_name 未定义”。

【问题讨论】:

    标签: javascript node.js for-loop


    【解决方案1】:

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

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

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

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

    另外,我不明白为什么你需要一个循环,因为你并没有真正循环遍历任何东西。


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

    for (...) {
      let _name
    }
    
    message.channel.send(_name)
    

    _name 需要在 for 循环块之外。

    let _name
    
    for (...) {
      _name = ...
    }
    
    message.channel.send(_name)
    

    总的来说,我在您的用例的实现中看到了很多问题。我建议您退后一步,重新考虑您的代码。

    【讨论】:

      【解决方案2】:

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

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

      根本不执行并且

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

      无限执行。

      【讨论】:

        猜你喜欢
        • 2013-12-06
        • 2021-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-26
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多