2012-09-28 33 views
6

有沒有一種很好的方式來循環使用jQuery每個循環僅json對象的前3項?如何在jQuery中限制json數據上的每個循環?

我正在考慮相當於.slice(start,end)函數。

var data = [ 
{"Id": 10004, "PageName": "club"}, 
{"Id": 10040, "PageName": "qaz"}, 
{"Id": 10059, "PageName": "ee"}, 
{"Id": 10089, "PageName": "dd"}, 
{"Id": 10095, "PageName": "hh"} 
]; 

$.each(data, function(i, item) { 
    alert(item.PageName); 
    // somehow break at item 3 
});​ 

回答

27
var data = [ 
{"Id": 10004, "PageName": "club"}, 
{"Id": 10040, "PageName": "qaz"}, 
{"Id": 10059, "PageName": "ee"}, 
{"Id": 10089, "PageName": "dd"}, 
{"Id": 10095, "PageName": "hh"} 
]; 

$.each(data, function(i, item) { 
    alert(item.PageName); 
    return i<2; 
});​ 

,當你返回false每個停止。

從文檔:

We can break the $.each() loop at a particular iteration by making the callback function return false. Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

2

你可以試試這個

$.each(data, function(i, item) { 
    if(i>2) return false; 
    alert(item.PageName); 
});​ 

DEMO

+2

嗯,這將迭代數組中的所有元素。 – VisioN

+0

@VisioN不,它不會。查看aquinas的答案的細節。 – Barmar

+1

@Barmar當前答案已更新。見修訂。 – VisioN

7

試試這個

$.each(data.slice(0,3), function(i, item) { 
    alert(item.PageName); 
});​ 
+0

這是否快於簡單地停止循環'3的增量我?' – Ohgodwhy

+0

它應該無關緊要的小json對象..如果你的json對象有大量的數據會怎麼樣..如果thta的情況下,你是不必要地循環到 –

+0

我完全同意你的陳述;我只是因爲好奇而問你是否知道。 – Ohgodwhy

-1
$.each(data, function(i){ 
    //i is 0 based, so 3 is really 2. 
    if(i == 2){ 
     //exit the loop on the 3rd iteration of the object. 
     return false; 
    } 
}); 
0
$.each($(data).slice(0,3), function(i,item){ 
    console.log("\t",item.Id); 
}); 
0

你也可以通過它使用嘗試循環for循環

這裏的它是如何做到

 for(var i =0;i<3;i++){ 

     alert("Id is"+d[i].id) ; 

    } 

而且循環遍歷整個Json數組使用以下內容

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

     alert("Id is"+d[i].id); 
    }