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
function save_i(){
var a = [];
for(var i = 0;i<10;i++){
a[i] = function(i){
return function() {
return i;
};
}(i);
}
return a;
}
var c = save_i();
for(var i = 0;i<10;i++){
console.log(c[i]());
//已經(jīng)變?yōu)橐来屋敵?}
在執(zhí)行點擊事件之前,for循環(huán)已經(jīng)執(zhí)行完,也就是最終獲取的是最后 i 的值5。
呆神:綁定 和 點擊 是兩個事件 點擊是用戶交互的時候發(fā)生 綁定在引擎編譯代碼的時候就發(fā)生了~
宇神:這樣理解吧,你把點擊事件當做一個下車事件,而火車從1-4,到4時你才能下車執(zhí)行事件,此時值為4.
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...
function save_i(){
var a = [];
for(var i = 0;i<10;i++){
a[i] = function(i){
return i;
};
}
return a;
}
var c = save_i();
for(var i = 0;i<10;i++){
console.log(c[i](i));
}
a[i] = function(i){
return i;
};
Each i in return refers to the same external i, which is 10
var fns=[];
function test(){
for(var i=0;i<10;i++){
(function(j){
fns.push(
function(){
console.log(j);
}
);
})(i);
}
}
test();
for(var k=0;k<fns.length;k++){
fns[k]();
}
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(){
var a = [],
i = 0;
for(;i<10;i++){
a[i] = function(i){
return i;
}(i);
}
return a;
}