Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch last iteration inside $.each in jQuery?

var arr = {'a':fn1,'b':fn2,'c':fn3}

$.each(arr,function(name,func){
(do something particular for the last iteration)
...
})

It'll be best if no additional variables are used.

EDIT: I mean LITERALLY last one,which is the last pair I type them.

like image 559
omg Avatar asked Sep 09 '09 11:09

omg


People also ask

What is the use of jQuery each() function?

each(), which is used to iterate, exclusively, over a jQuery object. The $. each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

How to break each loop in jQuery?

To break a $. each or $(selector). each loop, you have to return false in the loop callback. Returning true skips to the next iteration, equivalent to a continue in a normal loop.

How to each array in jQuery?

Answer: Use the jQuery. each() function each() or $. each() can be used to seamlessly iterate over any collection, whether it is an object or an array. However, since the $. each() function internally retrieves and uses the length property of the passed array or object.

What is each loop in jQuery?

jQuery's each() function is used to loop through each element of the target jQuery object — an object that contains one or more DOM elements, and exposes all jQuery functions. It's very useful for multi-element DOM manipulation, as well as iterating over arbitrary arrays and object properties.


1 Answers

Your example variable is called 'arr', but it's not an array at all (it's an object). This makes it a little confusing.

When iterating over an object, there's no such thing as a "last" property, because the order of properties is undefined by design.

When iterating over an array, you can simply compare the first parameter of the callback with the (array.length-1) to detect the last iteration.

In code (for arrays):

var arr = [ "a","b","c" ];

$.each(arr, function(i,val) { if (i == arr.length-1) ... });
like image 106
Philippe Leybaert Avatar answered Oct 16 '22 09:10

Philippe Leybaert