jQuery 如何跳过 $.each() 的第一次迭代?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1396638/
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:21:03  来源:igfitidea点击:

How do I skip the first iteration of an $.each()?

jquery

提问by mwHymanson

I have a JSON list that I want to iterate over, but skip the first entry, like thus:

我有一个要迭代的 JSON 列表,但跳过第一个条目,如下所示:

$.each(
    data.collection,
    function() { DoStuffButOnlyIfNotTheFirstOne(); }
);

Any ideas?

有任何想法吗?

回答by Tomas Aschan

Is this good enough?

这够好吗?

$.each(data.collection.slice(1), DoStuff);

回答by chaos

$.each(
    data.collection,
    function(i) {
        if(i)
            DoStuffButOnlyIfNotTheFirstOne();
    }
);

or, probably more efficiently:

或者,可能更有效:

$.each(
    data.collection.slice(1),
    function() {
        DoStuff();
    }
);

回答by Jon Galloway

You can use the good old firstFlag approach:

您可以使用旧的 firstFlag 方法:

var firstFlag = true;
$.each(
data.collection,
  function() { 
    if(!firstFlag) DoStuffButOnlyIfNotTheFirstOne(); 
    firstFlag = false;
}

But instead, I'd recommend that you filter your data collection first to remove the first item using a selector.

但相反,我建议您首先过滤数据集合以使用选择器删除第一项。

回答by Rohan Kumar

Why not using sliceto remove the first one and then use $.eachwithout any condition (it might increase your performance for large set of arrays)

为什么不使用slice删除第一个,然后在没有任何条件的情况下使用$.each(它可能会提高大型数组的性能)

var collection = data.collection.slice(0 , 1);
$.each(collection,function() {
   DoStuff();
});

回答by Philippe Leybaert

$.each(
    data.collection,
    function(i) { if (i>0) DoStuffButOnlyIfNotTheFirstOne(); }
);