where:
var arr = [];
for (var i = 0; i < 2; i++) {
arr[i] = function () {
console.log(i);
}
}
arr[0]();
arr[1]();
Output:
2
2
Analysis:
The function inside the for loop is never executed.
When the function is executed, it cannot find its own value of variable i in its own scope. According to the scope chain search principle, it is necessary to search in the upper layer scope (that is, the global scope). There is a variable i in the global scope, because When the function is executed, the loop has already been executed. When i = 2, the loop is completed, the printed i is a global variable, so the output of both functions isGlobal variable iValue of 2
The key point of this problem is that the variable i is global, and the output of the function when the function is executed is the value of i under the global action.
let:
let arr = [];
for (let i = 0; i < 2; i++) {
arr[i] = function() {
console.log(i);
}
}
arr[0]();
arr[1]();
Output:
0
1
analysis:
Since the variable i declared with let has block-level scope, two block-level scopes are generated after the end of the loop.
The two block-level scopes generated have their own variables i. These are two variables, which do not affect each other, because in different block-level scopes, two variables i are still stored in the array after the loop is over. Function During execution, there is still no own variable i, and we still have to look up the upper-level scope. In the current code, the upper-level scope of the function is actually the block-level scope generated by the loop, so the two array functions need to be executed. Find the value of i in the corresponding block-level scope.
The key point of this problem is that each loop will generate a block-level scope. The variables in each block-level scope are different. When the function is executed, it outputs its own upper level (block-level scope generated by the loop) Under value