Réponse acceptée !
Re,
et bien tu n'as pas le choix, c'est le seul moyen....
Tien voilà ce qu'en dis l'auteur de la librairie prototypejs:
Many JavaScript authors have been misled into using the for.in JavaScript construct to loop over array elements. This kind of code just won't work with Prototype.
You see, the ECMA 262 standard, which defines ECMAScript 3rd edition, supposedly implemented by all major browsers including MSIE, defines numerous methods on Array (§15.4.4), including such nice methods as concat, join, pop and push, to name but a few among the ten methods specified.
This same standard explicitely defines that the for.in construct (§12.6.4) exists to enumerate the properties of the object appearing on the right side of the in keyword. Only properties specifically marked as non-enumerable are ignored by such a loop. By default, the prototype and the length properties are so marked, which prevents you from enumerating over array methods when using for.in. This comfort led developers to use for.in as a shortcut for indexing loops, when it is not its actual purpose.
However, Prototype has no way to mark the methods it adds to Array.prototype as non-enumerable. Therefore, using for.in on arrays when using Prototype will enumerate all extended methods as well, such as those coming from the Enumerable module, and those Prototype puts in the Array namespace (described in this section, and listed further below).
What is a developer to do?
You can revert to vanilla loops:
for(var index = 0; index < myArray.length; ++index) {
var item = myArray[index];
}
Or you can use iterators, such as each :
myArray.each(function(item) {
});
This side-effect enforcement of the true purpose of for.in
is actually not so much of a burden: as you'll see, most of what you
used to loop over arrays for can be concisely done using the new
methods provided by Array or the mixed-in Enumerable module. So manual loops should be fairly rare.
A note on performance
Should you have a very large array, using iterators with lexical closures (anonymous functions that you pass to the iterators, that get invoked at every loop iteration), such as each, or relying on repetitive array construction (such as uniq),
may yield unsatisfactory performance. In such cases, you're better off
writing manual indexing loops, but take care then to cache the length property and use the prefix ++ operator:
for(var index = 0, len = myArray.length; index < len; ++index) {
var item = myArray[index];
}