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

时间:2021-07-28 09:07:37

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?

有任何想法吗?

5 个解决方案

#1


38  

Is this good enough?

这够好吗?

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

#2


15  

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

or, probably more efficiently:

或者,可能更有效:

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

#3


2  

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.

但相反,我建议您先过滤数据集,然后使用选择器删除第一个项目。

#4


2  

Why not using slice to remove the first one and then use $.each without 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();
});

#5


0  

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

#1


38  

Is this good enough?

这够好吗?

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

#2


15  

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

or, probably more efficiently:

或者,可能更有效:

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

#3


2  

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.

但相反,我建议您先过滤数据集,然后使用选择器删除第一个项目。

#4


2  

Why not using slice to remove the first one and then use $.each without 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();
});

#5


0  

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