javascript - Pourquoi utilise pour...in for array iteration a bad idea

Mots clés : javascriptarraysloopsfor-loopiterationjavascript

meilleur 4 Réponses javascript - Pourquoi utilise pour...in for array iteration a bad idea

vote vote

95

var a = []; // Create a new empty array.  a[5] = 5;   // Perfectly legal JavaScript that resizes the array.    for (var i = 0; i < a.length; i++) {      // Iterate over numeric indexes from 0 to 5, as everyone expects.      console.log(a[i]);  }    /* Will display:     undefined     undefined     undefined     undefined     undefined     5  */
var a = [];  a[5] = 5;  for (var x in a) {      // Shows only the explicitly set index of "5", and ignores 0-4      console.log(x);  }    /* Will display:     5  */
// Somewhere deep in your JavaScript library...  Array.prototype.foo = 1;    // Now you have no idea what the below code will do.  var a = [1, 2, 3, 4, 5];  for (var x in a){      // Now foo is a part of EVERY array and       // will show up here as a value of 'x'.      console.log(x);  }    /* Will display:     0     1     2     3     4     foo  */
vote vote

88

var array = []; array[2] = 'c'; array[1] = 'b'; array[0] = 'a';  for (var p in array) {   //... p will be "2", "1" and "0" on IE } 
Array.prototype.last = function () { return this[this.length-1]; };  for (var p in []) { // an empty array   // last will be enumerated } 
for (var prop in obj) {   if (obj.hasOwnProperty(prop)) {     // prop is not inherited   } } 
for (var prop in obj) {   if (Object.prototype.hasOwnProperty.call(obj, prop)) {     // prop is not inherited   } } 
vote vote

74

Array.prototype.myOwnFunction = function() { alert(this); } a = new Array(); a[0] = 'foo'; a[1] = 'bar'; for(x in a){  document.write(x + ' = ' + a[x]); } 
 0 = foo 1 = bar myOwnFunction = function() { alert(this); } 
for(i=0,x=a.length;i<x;i++){  document.write(i + ' = ' + a[i]); } 
 0 = foo 1 = bar 
vote vote

61

Array.prototype.foo = 1; var arr = []; arr[5] = "xyz";  console.log("for...of:"); var count = 0; for (var item of arr) {     console.log(count + ":", item);     count++;     }  console.log("for...in:"); count = 0; for (var item in arr) {     console.log(count + ":", item);     count++;     } 
for...of:  0: undefined 1: undefined 2: undefined 3: undefined 4: undefined 5: xyz  for...in:  0: 5 1: foo 

Questions similaires