Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reason why jQuery.each doesn't rely on Array.forEach when available? [duplicate]

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 ?

like image 970
Samuel Rossille Avatar asked Feb 22 '13 04:02

Samuel Rossille


1 Answers

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.

like image 145
chug187 Avatar answered Sep 17 '22 20:09

chug187