Does anyone why is the otherwise excellent jQuery.each
function is designed differently from the (now) native Array.forEach
? F.ex:
var arr = ['abc','def'];
arr.forEach(function(entry, index) {
console.log(entry); // abc / def
});
This makes absolute sense. But jQuery chose to put the index
as first argument:
$.each(arr, function(index, entry) {
console.log(entry);
});
Does anyone know the reasoning behind this design decision? I have always used $.each
extensively, but it always bugged me that the index was the first argument as it is rarely used. I know jQuery implemented a direct reference through this
but it’s very confusing if you do:
?var arr = ['abc','def'];
$.each(arr, function() {
console.log(this === 'abc'); // false both times, since this is a String constructor
});?????????????????????????????
Not that it bothers me so much, I prefer to use native polyfills for the most common new array functions, but I have always been curious about the design decision. Maybe it was made in older times before browsers implemented native forEach
and legacy support prevented them from changing it, or...?
Or maybe, it is designed this way because is can be used on native objects too, than then it "makes sense" to put the key before value in the callback...?
Sidenote: I know underscore.js (and maybe other libraries) does it the other way around (more similar to the native function).
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…