如何限制 jquery 中 json 数据的每个循环?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12648063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 11:53:58  来源:igfitidea点击:

How to limit an each loop on json data in jquery ?

jqueryjsoneach

提问by Asimov4

Is there a nice way to loop on only the first 3 items of a json object using the jquery each loop?

有没有一种很好的方法来使用 jquery each 循环只循环 json 对象的前 3 个项目?

I am thinking of an equivalent of the .slice(start,end)function.

我正在考虑.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
});?

回答by aquinas

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;
});?

each stops when you return false.

当您返回 false 时,每个都会停止。

From the docs:

从文档:

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.

我们可以通过使回调函数返回 false 来在特定迭代中中断 $.each() 循环。返回非 false 与 for 循环中的 continue 语句相同;它将立即跳到下一次迭代。

回答by Sushanth --

Try this

尝试这个

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

回答by The Alpha

You may try this

你可以试试这个

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

DEMO.

演示

回答by Shanimal

$.each($(data).slice(0,3), function(i,item){
  console.log("\t",item.Id);
});

回答by Denzil Sequeira

You can also try to loop through it using a for-loop

您也可以尝试使用 for 循环遍历它

here's how it's done

这是它的完成方式

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

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

     }

And to loop through the whole Json array use the following

并循环遍历整个 Json 数组,使用以下命令

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

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

回答by Ohgodwhy

$.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;
  }
});