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
迷茫2017-06-26 10:59:37
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
;
PHP中文网2017-06-26 10:59:37
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.
学习ing2017-06-26 10:59:37
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~~