【问题标题】:My javascript for loop is only printing 1 rows out of an array with 3 rows我的 javascript for 循环仅从 3 行数组中打印 1 行
【发布时间】:2013-04-29 02:29:11
【问题描述】:

我不知道 for 循环中的正确条件应该是什么,该循环遍历一个数组,该数组的长度取决于我从表中提取并添加到数组中的行数。该数组当前有三行,但 for 循环只打印出两行。我的代码:

//my database query 

query.find({
  success: function(results) {

//this for loop works fine

    for (i = 0; i < results.length; i++){

        eventID = results[i].id;
       activity = results[i].get("activity");
        scene = results[i].get("location");
        neighborhood = results[i].get("neighborhood");
        date = results[i].get("date");
        details = results[i].get("details");
        time = results[i].get("time");
        objIDs.push(eventID);

//each row gets pushed into an array

       search.push([activity, scene, neighborhood, date, details, time]);


        //I empty a div on a page that uses the ajax load() method to load an html page.I replace that html with the array of query results. 

             $('#div1').empty();

       //there are currently 3 rows in my array, but when I loop through it and append() the </br>rows to the div, only one gets printed. I've tried changing the comparison operator to </br>different things but nothing works. I'm definitely getting all the rows from the query because when I alert() the search array I see all the rows. 

       for (i = 0; i <= search.length; i++) {

            $('#mainDiv').append("<div id='event'>" + search[i].join(' ') + "<a href='#' class='interested'>Interested?</a></div>");
        } 

    };// closes for
    },//closes success

  error: function(error) {
    alert("Error: " + error.code + " " + error.message);
  }
}); //closes find 

【问题讨论】:

  • 您是否检查了查询响应是否返回了您需要的所有对象?
  • search 在哪里初始化? search 中真的有 3 行还是 results 中有 3 行?

标签: javascript for-loop conditional-statements


【解决方案1】:

您在for 中有一个for,当您对其进行迭代时,您的搜索尚未完全初始化。

};// closes for

    for (i = 0; i <= search.length; i++) {

        $('#mainDiv').append("<div id='event'>" + search[i].join(' ') + "<a href='#' class='interested'>Interested?</a></div>");
    } 

},//closes success

【讨论】:

    【解决方案2】:

    虽然以下是一个问题,但它可能不是问题。但是,由于我无法删除此帖子(我必须登录或其他什么?)它仍然是一个工件。请注意它,即使是其他问题。


    代码在 嵌套 循环中使用相同的 i 变量 - 并在两个循环中递增 i

    使用不同的变量。

    【讨论】:

      猜你喜欢
      • 2021-03-07
      • 1970-01-01
      • 2015-11-01
      • 2017-09-08
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      • 1970-01-01
      • 2013-09-16
      相关资源
      最近更新 更多