Is there a reason jQuery.each doesn't rely on Array.forEach if available?

While copying the underscore library into the source code, I found that _.each relies on the ECMAScript 5 Array.forEach API when it is available:

 var each = _.each = _.forEach = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (iterator.call(context, obj[i], i, obj) === breaker) { return; } } } else { for (var key in obj) { if (_.has(obj, key)) { if (iterator.call(context, obj[key], key, obj) === breaker) { return; } } } } }; 

I noticed that jQuery.each (static, not .each for the jQuery shell) only performs the traditional for , which calls the callback function, whether forEach is available or not. Is there a reason for what I missed?

+6
source share
1 answer

Probably because the two are different in implementation - Array.forEach passes the array element as the first parameter, and the index as the second. jQuery.each passes the index first, the array element sends.

In fact, probably the best source of discussion is here when the stack overflows:

jQuery.each differs from Array.forEach native array

It was supposed to be a mistake, so many sites implemented jQuery.each, expecting an index first that they could not possibly change them.

+1
source

All Articles