8

Is there any difference between Jquery.each() and Array.prototype.forEach() method since array.forEach() method can also be used to loop over array-like objects with length property.The only difference i see is placement of arguments ,what else can be the difference in them?

 I found this:
 var obj = { one:1, two:2, three:3, four:4, five:5 };

jQuery.each(obj, function(i, val) {
  $("#" + i).append(document.createTextNode(" - " + val));
});

What i wan to know is ,do jquery.each() invokes function for object without length property??

2
  • Here's the answer : stackoverflow.com/questions/6611190/… Commented Jul 5, 2013 at 13:25
  • 1
    You changed your question. Now you're asking if jQuery's $.each is overloaded to enumerate any object. Why not just try it? Commented Jul 5, 2013 at 13:34

2 Answers 2

17
  • Placement of arguments in the callback.

  • Quantity of arguments in the callback (The .forEach() gives you get a reference to the original collection.)

  • Default this value in the callback. (In jQuery it's the current item, in .forEach() it's the JavaScript default)

  • Ability to manually set the this value in the callback. (jQuery doesn't give this option, .forEach() lets you via a third argument.)

  • Avoidance of non-defined properties on sparse Arrays. (The .forEach() avoids them, jQuery includes them.)


They're very differently behaving methods. jQuery's doesn't make any attempt to be compliant with or complimentary of the standard behaviors.

Sign up to request clarification or add additional context in comments.

1 Comment

What i wan to know is ,do jquery.each() invokes function for object without length property??
5

In addition to Crazy Train's answer:

What i wan to know is ,do jquery.each() invokes function for object without length property??

Read the source:

// args is for internal usage only
each: function( object, callback, args ) {
  var name, i = 0,
      length = object.length,
      isObj = length === undefined || jQuery.isFunction( object );

  if ( args ) {
    ...

  // A special, fast, case for the most common use of each
  } else {

    if ( isObj ) {
      for ( name in object ) {
      }
      ...
    }
  }
  return object;
},

So you can see if there is no length property, or it has the value undefined, then jQuery thinks it's a plain object and will do a for..in loop over the enumerable properties with no guard against inherited properties.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.