Pages

for in with array : don't use it

itération sur les indices et non sur les valeurs
var arr = [ 'a', 'b', 'c' ];
for (var key in arr) { console.log(key); }
0
1
2
De plus, 
 var arr = [ 'a', 'b', 'c' ];
 arr.foo = true;
 for (var key in arr) { console.log(key); }
0
1
2
foo
correction : hasOwnProperty(key) !
for (var key in arr) {
    if (arr.hasOwnProperty(key)) {
        console.log(key);
    }
}
Finalement, on choisit
  • for (var i=0; i<arr.length; i++) {
        console.log(arr[i]);
    }
  • arr.forEach(function (elem) {
        console.log(elem);
    });