【问题标题】:Node.js Problems with for(var i = 0for(var i = 0) 的 Node.js 问题
【发布时间】:2015-10-09 09:43:03
【问题描述】:

我有一个小问题。我正在尝试使用节点从 mySQL 获取一些数据,并且当我通过我得到的行进行 for 循环时,我总是得到 1 个索引太多或 1 个索引/行不包含在我的以下代码。

connection.query("SELECT clientid, profileid FROM ts3bot_in", function(err, rows) {
    if (!err) {
        console.log("Found " + rows.length);
        console.log(rows);

        for (var i = 1; i < (rows.length); i++) {
            console.log(i);
        }
    }
}

所以我的意思是:当我在我的数据库表中找到 1 行时,我得到 i = 0 和 i = 1。如果有 2 行,我得到 i=0、i=1 和 i=2 .

希望你们中的某个人可以帮助我。

最好的问候,ndslr。

【问题讨论】:

  • 你为什么要做rows.size?这不应该是 rows.length 吗?
  • var i = 0; i &lt; rows.length 不应该足够吗?请注意= 的缺席...
  • @Alex 是的,我之前只是尝试过 .size 并忘记再次将其反转为 .length。
  • @moonwave99 我也试过我
  • rows 中有什么内容?它应该是一个简单的数组,并且您应该能够迭代一个简单的数组。

标签: javascript mysql node.js


【解决方案1】:

试试这个

connection.query("SELECT clientid, profileid FROM ts3bot_in", function(err, rows) {
    if (!err) {
        console.log("Found " + rows.length);
        console.log(rows);

        for (var i = 0; i < rows.length; i++) {
            console.log(i);
        }
    }
}

请记住,数组是基于零索引的 - 第一项将为 0。第二项为 1。等等...

rows[0] 将始终是数组中的第一项。

您在哪里 console.log(i) 第一项将始终为 0。
如果您希望它为第一项显示 1,则需要执行 console.log(i+1) - 以克服基于零的索引。

或者,你可以试试.forEach

connection.query("SELECT clientid, profileid FROM ts3bot_in", function(err, rows) {
    if (!err) {
        console.log("Found " + rows.length);
        console.log(rows);

        rows.forEach(function(row, i) {
            console.log(row); // the actual item
            console.log(i); // the index - again, zero based
        })
    }
}

【讨论】:

  • 在 for 循环解决方案中,行索引应该从 0 开始。
  • @bluefog 抱歉,是的...错字!或者更确切地说是复制/粘贴错误;-) - 已编辑
  • 您的第二个答案效果很好。感谢您的帮助
猜你喜欢
  • 1970-01-01
  • 2011-07-27
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
  • 2012-05-09
  • 1970-01-01
  • 2016-10-16
  • 1970-01-01
相关资源
最近更新 更多