While digging into the source code of the underscore library, I found at that _.each
relies on an ECMAScript 5 API Array.forEach
whenever 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 (the static one, not the .each method of a jQuery wrapper) does just a traditional for
that calls the callback function, no matter if forEach
is available or not. Is there a reason for that that I missed ?
It's probably because the two differ 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 send.
Actually probably the best discussion source is right here on stack overflow:
jQuery.each implementation differs from native Array.forEach
Their guess being that it was a mistake - so many sites have implemented jQuery.each, expecting the index first, that they can't feasibly reverse them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With