Search code examples
javascriptarraysfor-loopfor-in-loop

Delete item from array , why for and for in output are different?


var arr = ["a", "b", "c",null,undefined];

delete arr[0];

for (var i = 0,j=arr.length; i < j; i++) {
    console.log(arr[i]);
    /*
    undefined
    b
    c
    null
    undefined
    */
}

for (var o in arr) {
    console.log(arr[o]);
    /*
    b
    c
    null
    undefined
    */
}

who can tell me why the output is different?


Solution

  • you have access by key;

    array index is key of array object

    using delete keyword, remove object key because

    delete arr[0]; // key "0" deleted!
    

    ok?

    and see this

    var arr = ["a", "b", "c",null,undefined];
    delete arr[0]; // key "0" deleted!
    
    // access by i,  with key : 0
    for (var i = 0,j=arr.length; i < j; i++) {
        console.log(i);
        /*
        0 
        1 
        2 
        3 
        4 
        */
    }
    
    // access by object key, without key : 0
    for (var o in arr) {
        console.log(o);
        /*
        1
        2
        3
        4 
        */
    }​​​​​​​​​​
    

    good luck!