Why is it output 10 times? Shouldn’t the 10 pushed in be 1 - 9? Please ask an expert to answer this question
function save_i(){
var a = [];
for(var i = 0;i<10;i++){
a[i] = function(){
return i;
}
}
return a;
}
var c = save_i();
for(var i = 0;i<10;i++){
console.log(c[i]());
//10次 10
}
You only need to create a closure function to save the i value when the for loop is executed, and it can be output in sequence
Articles I have read in the past
Understanding closures requires you to write a code and then use it in your own code. Other than that, you can only memorize it by rote.
Old-school Chinese like to let their children carry things when they are very young, but they don’t know what it means and sometimes they can’t explain it clearly. They hope that they will understand it naturally at some point in the future
The above
If you have You have a certain basic knowledge. It is recommended to read the logs I wrote. If you still don’t understand, leave a message and ask me.
http://user.qzone.qq.com/2084...
Each i in return refers to the same external i, which is 10
The scope of var variables is function scope, not block-level scope
The scope chain has been generated when it was created,
c[i] = function(i){ return i; };
When running, the current scope does not have i, but the i of the upper scope save_i() has changed into 10. Do you think the result is 0~9? Do you think the upper scope is the global scope?a[i] is a bunch of functions when assigned, that is, it is not executed, nor does it get i, and its scope does not get i either
When you execute it below, this bunch of functions start to look for the i that can be obtained in their own scope, which is the 10 after the loop is executed
The
var keyword declares the variable scope to be the function scope, so the i variable in the for loop will be promoted. It will be ok if the poster changes the section in the for loop to a self-executing function. eg:
function save_i(){
}