For (vari0, arr []; I & lt; 3; I ++) {arr. push (function () {alert (I)}) ;}arr [0] () ;?? The result is not 0arr [1] () ;?? All for (vari0, arr []; I & lt; 3; I ++) {arr. push (function (I) {returnfunction () {for (var I = 0, arr = []; I <= 3; I ++ ){
Arr. push (function () {alert (I )});
}
Arr [0] (); //? The result is not 0.
Arr [1] (); //? All four
After modification
For (var I = 0, arr = []; I <= 3; I ++ ){
Arr. push (
(Function (I ){
Return function (){
Alert (I );
}
}) (I)
);
}
The closure can solve this problem. Why does I read the final result of the I variable for the first time?
Can the great god analyze the specific steps for executing the first code? Reply content: Answer the question,
Thank you!! This problem uses js
Pre-interpretation + scope + closureThis can be explained. For ease of understanding, I will illustrate the following two figures:
- This is the previous running process:
Legend: the green box shows the stack memory for function execution, pink is the heap memory, and 0XAA is the memory address (the string storing the function is not executed, it is executed only when the function is called). It can be seen from top to bottom in the main process.
In the original version score before modification, when each item in arr is executed, it will go to the upper-level scope to search for I, and after the for loop is executed, it will become 4, therefore, the execution results of each item in arr are the same. In the original version score before modification, when each item in arr is executed, it will go to the upper-level scope to search for I, and after the for loop is executed, it will become 4, therefore, the execution results of each item in arr are the same.
In the pre-interpretation phase, functions are stored in the heap memory as strings and executed only when they are actually executed. What is stored in the array is actually a pointer to the heap memory, I was not passed in. I was passed in only when I was executed.
- This is the modified running process:
In the modified version, each time a new item is added to arr, the self-executed function is executed and I is passed into the self-executed function as a parameter. The key point is In the modified version, each time a new item is added to arr, the self-executed function is executed and I is passed into the self-executed function as a parameter. The key point is
In function (I) {...} (I), the first I is the form parameter of the function. It is a private variable and has nothing to do with the outside I. It is protected by the private scope.,
The second I is the foreign I of the function.(That is to say, the first I is just a confusing amount, and changing it to k is the same result, except that I is assigned to k.) In this way, each time a self-execution function is triggered, it is equivalent to storing the variable I of the current loop. When each item in arr is executed, a function of the new address returned by the self-executed function is called. The function of this new address searches for I in the upper-level scope, the upper-level scope is the self-executed function when the new address is formed (that is, the address 0xA1 is obtained from the first return execution of the 0XAA function, when 0XAA is executed for the first time, the stack memory is the upper-level scope of 0XA1. In the upper-level scope, I (or the shape parameter in the upper-level scope) is the I he is looking, therefore, you can achieve the desired effect. This mechanism to protect private variables is the closure.
As for js defects and bugs, you can take a break (at least this problem is not a bug ). If you are familiar with automatic transmission, you have to laugh at the manual transmission of the car clutch, the combination of the gas, the gas, and easily turn off the fire. Is it interesting? This is how people work, at least as a front-end language. I didn't say that I had to compete with industrial languages.
Here
IYes
ReferenceAs long as you understand this, there is nothing hard to understand.
var arr = [], i;for (i = 0; i < 3; i++) { arr.push(function() { console.log(i); });}console.log(i) // 3arr[0](); // 3i = 5;arr[0](); // 5
The key to understanding this problem is execution context. Simply put, when a function is called, it can "see" where the variable name is. To simplify the problem, you can consider that execution context is composed of only the following two types: 1) Global scope, that is, Global variables; 2) variables defined in the function when each function is called.
When a function is called,
An object is generated (activation object), which includes the variables and arguments defined in the called function and their values.Global scope variables are saved by global objects.
When a function tries to read a variable, it will first read from the latest object (like prototyping, but note that this is close to where the function is defined, instead of where the object is executed. If it is read, it will not continue. Otherwise, it will read the object of the upper-level context until the global context. When a function is executed, the object connected to it will be canceled by reference (and then cleaned by GC ). That is to say, if you have the following code:
var globalVar = 0;var outerVar;var innerVar;console.log(globalVar);console.log(outerVar);console.log(innerVar);function outer() { function inner() { var innerVar = 2; console.log(globalVar); console.log(outerVar); console.log(innerVar); } var outerVar = 1; console.log(globalVar); console.log(outerVar); console.log(innerVar); inner();}outer();
About this question:
Aside from the interpretation of the variable reference of the execution environment scope chain, we can analyze and solve the problems mentioned by the subject from some execution steps and even semantics.
for(var i=0,arr=[];i<=3;i++) {arr.push(function(){alert(i)});}
for (var i = 0, arr = []; i <= 3; i++) { arr.push(function () { alert(j) });}
Because js does not have block-level scope
The body of the for Loop is not a scope.
Your first code is equivalent to the following
var arr=[];var i=0;arr.push(function(){console.log(i);});i++;arr.push(function(){console.log(i);});i++;arr.push(function(){console.log(i);});i++;arr.push(function(){console.log(i);});i++;arr[0]();arr[3]();