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 ?