Advantages of .each () in jQuery over Traditional For Loops

One of my colleagues suggested I use the jQuery .each() function through the javascript for loop to go through the DOM elements on my page, I am not new to jQuery, but did not understand the true reason why developers tend to use .each() for the javascript loop. Can anyone explain this to me?

+4
source share
5 answers

If you want to iterate with a for loop, you need to increase the index:

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

and then you should get the actual value using the index:

 var value = arr[i]; 

.each performs both of these functions for you and passes the values ​​to the function:

 $(...).each(function(i, value) { // actual interesting part of the loop... }); 

It simply saves the template code by incrementing the index and getting the value at that index.

Variables defined in the .each function .each also closed (i.e., inside closure ), so the equivalent code (considering the loop and closing the variable, as well as setting this , as well as violating the return value of false ) can be something like this:

 (function() { for(var i=0; i<arr.length; ++i) { var ret = (function(index, value) { // actual interesting part of the loop... }).call(arr[i], i, arr[i]); if(ret === false) break; } })(); 

which is a bit more to enter.

In terms of runtime performance, .each (not surprisingly) slower than the raw for loop, because it does much more than the raw for loop.

+6
source

Its very easy to use.

But it is slow, as shown in this test result. http://jsperf.com/jquery-each-vs-for-loop/214

+2
source

Because it's easier and cleaner to do

 $jqExpr.each(function(i, el){ /* YOUR CODE */ }); than for(var i=0; i < $jqQExpr.length; i++){ el = $jqExp[i]; /* YOUR CODE */ } 
+1
source

It is slower, but more expressive (shorter), and also sets closures. Also, in jQuery collections, it integrates well into the chain; while for simple arrays I would suggest using my own .forEach method.

+1
source

For me, there is also an important side effect of closing benefits if you use each, not for.

Consider the code below (I am using coffeescript, as I found ..), which warns of all links with their href value:

 $("a").each (i, e)-> href = $(e).attr('href') $(e).on "click" alert(href) 

If you translate it into a simple loop, for example:

 for e in $("a") href = $(e).attr('href') $(e).on "click" alert(href) 

This code will not work since the href variable is not enclosed in closure ...

0
source

All Articles