javascript - Why is the result 3 instead of 2?
学习ing
学习ing 2017-06-26 10:57:37
0
4
699
function F(){
    var arr=[],i;
    for(i=0;i<3;i++){
        arr[i]=function(){
            return i;
        };
    }
    return arr;
}

arr[0]();//3
arr[1]();//3
arr[2]();//3
学习ing
学习ing

reply all(4)
迷茫

for(i=0;i<3;i++){loop body}The execution process is to assign the initial value 0, and then execute the judgment statement i<3. If it is true, execute the loop body. After the loop body is executed Execute i++; So when i is executed to 2, i<3 is true, execute the loop body, and then i++, at this time i is equal to 3, then judge i<3, judge it as false, and do not execute the loop body, exit the loop, at this time i=3;

巴扎黑

After the last for loop, i++ changed i to 3

Ty80

This question can be easily seen using breakpoints. In fact, it is a problem of function execution timing. The function is executed when it is called. After the loop is executed, i=3. When calling the function in the array, i can only for 3.

学习ing

js is executed sequentially. First, all loops are executed. During the execution process, arr[0]= function(){return i;}, arr[1]= function(){return i;}, arr[2] = function(){return i;}At the same time, program i after looping to 3, and then call arr[0]() and other calls. At this time, i in the scope is 3, so it will always be 3.

PS: For this question, you should execute arr = F() first, otherwise an error will be reported~~

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!