2013-05-04 24 views
-1

我不知道正確的條件應該在for循環中通過一個數組循環,該數組的長度將根據行數在我從中拉出並添加到數組中的表中。該數組目前有三行,但for循環僅打印出兩行。我的代碼:我的JavaScript for循環僅打印出3行數組中的1行

//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 
+1

您是否檢查查詢響應是否返回了您需要的所有對象? – steo 2013-05-04 23:54:12

+0

'search'初始化在哪裏? 「search」中真的有3行還是'results'中有3行? – 2013-05-05 00:05:10

+0

結果中有3行。 – Spilot 2013-05-05 00:31:40

回答

2

您在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

使用不同的變量。