javascript tutorial - [5 Solutions] “for…in” - javascript - java script - javascript array



Problem

Why is using “for…in” with array iteration a bad idea?

Solution 1:

The reason is that one construct:

var a = []; // Create a new empty array.
a[5] = 5;   // Perfectly legal JavaScript that resizes the array.

for (var we = 0; we < a.length; i++) {
    // Iterate over numeric indexes from 0 to 5, as everyone expects.
    console.log(a[i]);
}

/* Will display:
   undefined
   undefined
   undefined
   undefined
   5
*/
click below button to copy the code. By JavaScript tutorial team

Solution 2:

can sometimes be totally different from the other:

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
*/
click below button to copy the code. By JavaScript tutorial team

Solution 3:

Also consider that JavaScript libraries might do things like this, which will affect any array we create:

// Somewhere deep in our JavaScript library...
Array.prototype.foo = 1;

// Now we 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
*/
click below button to copy the code. By JavaScript tutorial team

Solution 4:

    Because for...in enumerates through the object that holds the array, not the array itself. If WE add a function to the arrays prototype chain, that will also be included. I.e.

    Array.prototype.myOwnFunction = function() { alert(this); }
    a = new Array();
    a[0] = 'foo';
    a[1] = 'bar';
    for(x in a){
     document.write(x + ' = ' + a[x]);
    }
    This will write:
    0 = foo
    1 = bar
    myOwnFunction = function() { alert(this); }
    
    click below button to copy the code. By JavaScript tutorial team

    And since we can never be sure that nothing will be added to the prototype chain just use a for loop to enumerate the array:

    for(i=0,x=a.length;i<x;i++){
     document.write(we + ' = ' + a[i]);
    }
    This will write:
    0 = foo
    1 = bar
    
    click below button to copy the code. By JavaScript tutorial team

    Solution 5:

    In addition to the other problems, the "for..in" syntax is probably slower, because the index is a string, not an integer.

    var a = ["a"]
    for (var we in a)	
        alert(typeof i)  // 'string'
    for (var we = 0; we < a.length; i++)
        alert(typeof i)  // 'number'
    
    click below button to copy the code. By JavaScript tutorial team

    Related Searches to javascript tutorial - “for…in”