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
}
黄舟2017-06-28 09:30:39
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]());
//已经变为依次输出
}
阿神2017-06-28 09:30:39
在执行点击事件之前,for循环已经执行完,也就是最终获取的是最后 i 的值5。
呆神:绑定 和 点击 是两个事件 点击是用户交互的时候发生 绑定在引擎编译代码的时候就发生了~
宇神:这样理解吧,你把点击事件当做一个下车事件,而火车从1-4,到4时你才能下车执行事件,此时值为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...
女神的闺蜜爱上我2017-06-28 09:30:39
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));
}
黄舟2017-06-28 09:30:39
a[i] = function(i){
return i;
};
Each i in return refers to the same external i, which is 10
黄舟2017-06-28 09:30:39
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
天蓬老师2017-06-28 09:30:39
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?
黄舟2017-06-28 09:30:39
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
巴扎黑2017-06-28 09:30:39
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;
}