简体   繁体   中英

var, loop in javascript, cannot understand the output, error

    var arr = [];
    for(var i=0; i<5; i++){
        arr[i] = function(){
            return i;
        };
    }
    document.write(arr[1]());

the output is 5, as I expected

but when i added i++ between return i; and the end of the for loop, like the code below,

    var arr = [];
    for(var i=0; i<5; i++){
        arr[i] = function(){
            return i;
        };
        i++;
    }
    document.write(arr[1]());

screen shows the error, Uncaught TypeError: arr[1] is not a function

i expected that output should be 6, but i cannot understand why.

Because you've got two increments for i , the assigned elements of the array will be 0 , 2 , and 4 . Element 1 is skipped.

The first assignment happens when i is 0. Then, i is incremented to 1 at the end of the loop, and then again to 2 in the third clause of the for loop header. So the next assignment is for element 2.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM