7

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??

Maizere Pathak.Nepal
  • 2,383
  • 3
  • 27
  • 41
  • Here's the answer : http://stackoverflow.com/questions/6611190/what-is-the-difference-between-eachselector-and-selector-each –  Jul 05 '13 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? –  Jul 05 '13 at 13:34

2 Answers2

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.

Sander
  • 526
  • 4
  • 10
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.

RobG
  • 142,382
  • 31
  • 172
  • 209