admin管理员组

文章数量:1416631

One of my colleague suggested me to use jQuery .each() function over javascript for loop to traverse through DOM elements on my page, I am not a newbie in jQuery, but never understood the real reason behind why developers tend to use .each() over for loop of javascript. Can anyone explain it to me?

One of my colleague suggested me to use jQuery .each() function over javascript for loop to traverse through DOM elements on my page, I am not a newbie in jQuery, but never understood the real reason behind why developers tend to use .each() over for loop of javascript. Can anyone explain it to me?

Share Improve this question edited Apr 24, 2013 at 12:59 georg 215k56 gold badges322 silver badges400 bronze badges asked Apr 24, 2013 at 12:46 SamSam 557 bronze badges 12
  • 3 Because it is shorter and doesn't explicitly define any extra variables. – VisioN Commented Apr 24, 2013 at 12:48
  • 2 And because you can chain it to a selector! – Ian Commented Apr 24, 2013 at 12:49
  • 1 it is more readable, than for loop ! – rab Commented Apr 24, 2013 at 12:49
  • 2 and you can pass it a function :) so you could wrap it in another function and pass your each function to the wrapper – Luke Commented Apr 24, 2013 at 12:49
  • 1 @Luke Which creates a new scope/closure for every iteration, which is usually good :) – Ian Commented Apr 24, 2013 at 12:49
 |  Show 7 more ments

5 Answers 5

Reset to default 6

If you want to iterate using a for loop, you have to increment the index:

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

and then you have to get the actual value using the index:

var value = arr[i];

.each does both of these for you and passes the values into a function:

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

It simply saves you the boilerplate code of incrementing the index and getting the value at that index.

The variables defined in an .each function are also closed over (i.e., within a closure), so the equivalent code (considering looping and variable closure, plus setting this, as well as breaking on a false return value) might be something like:

(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 quite a bit more to type.

In terms of execution performance, .each is (unsurprisingly) slower than a raw for loop, because it does much more than a raw for loop.

Its very easy to use

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

Because it is easier & cleaner to do

$jqExpr.each(function(i, el){
   /* YOUR CODE */
});

than

for(var i=0; i < $jqQExpr.length; i++){
  el = $jqExp[i];
  /* YOUR CODE */
}

It's slower, but more expressive (shorter) and it also sets up closures. Also, on jQuery collections it integrates well into chaining; while for plain arrays I would suggest using the native .forEach method.

There is also, for me, an important benefit closure side effect if you use each instead of for.

Consider the code below (I'm using coffeescript as I'm found of..) which alerts on all links with its href value:

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

If you "translate" it into a simple for loop like :

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

This code won't work as the href variable is not enclosed in a closure...

本文标签: javascriptBenefits of each() function in jQuery over traditional quotforquot loopsStack Overflow