【问题标题】:Why all the code works except the for-loop?为什么除了 for 循环之外的所有代码都有效?
【发布时间】:2019-05-01 10:06:46
【问题描述】:

我有一个代码,除了for循环,所有代码都在工作

let query = args.slice(1).join(' ');

client.database.query(`SELECT * FROM centres WHERE name="${query}"`, function (error, results, fields) {
    if (error) throw error;
    if (!results[0]) {
        message.channel.send(msg.cs.notExist)
    } else {
        client.database.query(`SELECT * FROM vehicules WHERE centre="${query}"`, function (err, res, field) {
            if (err) throw err;
            console.log(res.length)
            let i;
            for (i = 0; i === res.length; i++) {
                message.channel.send(res[i].name)
                console.log(i)
            }
            /*   message.channel.send(`${msg.cs.stats}${query}

            ${msg.abreviation.cdc}${client.functions.username(client, results[0].cdc)}
            ${msg.abreviation.cdca}${client.functions.username(client, results[0].cdca)}
            ${msg.cs.vehicule} ${results[0].vehicules}`)*/
        })
    }
});

res.length 的输出只有 4 个

【问题讨论】:

  • 不错的 SQL 注入。除此之外,请发帖minimal reproducible example
  • 投票关闭,因为这是一个印刷错误。 i === res.length 应该是 i < res.lengthi <= res.length

标签: javascript for-loop


【解决方案1】:
i=0; i===res.length; i++

for 循环中的条件是矛盾的。最初 i 为 0,并且给定循环条件使得 i 始终等于 res.length,然后在每次迭代后 i++ 将递增 i。假设 res 的长度为 7。由于该条件,循环将永远不会运行,因为 i 为 0。如果 i<res.length 是条件,那么它将正常工作。循环看起来像

for (i = 0; i < res.length; i++)

【讨论】:

    【解决方案2】:

    对我来说,你应该使用

    for(i=0; i <= res.length; i++){
      message.channel.send(res[i].name)
      console.log(i)
    }
    

    【讨论】:

      【解决方案3】:

      i = 0,而 res.length = 4。循环立即终止。将其更改为 i

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-01-27
        • 1970-01-01
        • 2020-03-01
        • 2021-05-29
        • 2017-06-04
        相关资源
        最近更新 更多