lov*_*356 0 javascript closures scope
我有以下小代码片段,具有以下预期和实际输出.我的问题很简单.为什么按顺序打印呢?以及如何打印预期的输出?
GR,
预期结果:
0
1
2
0
1
2
Run Code Online (Sandbox Code Playgroud)
实际结果:
0
1
2
3
3
3
Run Code Online (Sandbox Code Playgroud)
这是代码:
var functions = [];
for (var i=0; i<10; i++) {
console.log (i);
functions.push (function () {
console.log (i);
});
};
for (var j=0; j<functions.length; j++) {
functions[j] ();
};
Run Code Online (Sandbox Code Playgroud)
推入数组的函数不会记录i创建函数时的值,它们会记录i调用函数时的值.
一旦第一循环结束,的值i是10,因此任何的后调用将记录值的功能10.
如果要保留i不同状态的值,可以使用闭包来复制值:
for (var i=0; i<10; i++) {
console.log (i);
(function(){
var copy = i;
functions.push (function () {
console.log (copy);
});
})();
};
Run Code Online (Sandbox Code Playgroud)
局部变量copy将获取值i并保留该值.您还可以将值作为参数传递给函数:
for (var i=0; i<10; i++) {
console.log (i);
(function(copy){
functions.push (function () {
console.log (copy);
});
})(i);
};
Run Code Online (Sandbox Code Playgroud)