Reputation: 4211
Various JavaScript libraries (e.g. jQuery) offer an each
method:
$.each(myObj, myFunc);
What's the advantage over using the built-in for..in
loop:
for(var i in myObj) {
myFunc(i, myObj[i]);
}
In both cases I'd have to check for unwanted properties (usually functions), so I don't see why the each method is provided in the first place.
Upvotes: 0
Views: 309
Reputation: 532765
I can think of at least 3 advantages, though they are relatively small.
The disadvantages are some, small overhead -- you have to pay for what it does for you -- and the potential for confusing it with the $().each() method which is completely different.
Upvotes: 4
Reputation: 125538
As the jQuery $.each(object, callback)
explanation states
A generic iterator function, which can be used to seamlessly iterate over both objects and arrays.
In keeping in line with other utility functions, it provides an easy one line jQuery-fied syntax to use
Upvotes: 4
Reputation: 53626
The first takes 1 line, the other takes 3. You can do things like chaining, so you could call another array function after the first is done.
Upvotes: 2
Reputation: 70041
In the each example, you can use this
to call the currently selected element and work with it.
$("div img").each(function(i){
this.id = this.id + "_" + i;
});
Upvotes: 2