JavaScript变量范围 [英] JavaScript Variable Scope
问题描述
我对某些JavaScript代码有问题。
I'm having a problem with some JavaScript code.
脚本
setTimeout(function() {
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, i * 200);
}
}, 200);
输出
5,5,5,5,5而不是1,2,3,4,5
5, 5, 5, 5, 5 instead of 1, 2, 3, 4, 5
我可以理解为什么这不起作用,我想知道是否有人可以向我解释发生了什么,为什么它不工作!
I can kind of understand why this doesn't work, but I was wondering if someone could explain to me what's happening and why it's not working!
此外,如何解决这个范围问题?
Also, how can this scope problem be overcome?
推荐答案
setTimeout
回调函数是异步执行的, c $ c> console.log 调用引用相同的 i
变量,并且在执行时,for循环已结束且 i
包含4个。
The setTimeout
callback functions are executed asynchronously, all the console.log
calls you make refer to the same i
variable, and at the time they are executed, the for loop has ended and i
contains 4.
> setTimeout 调用一个接受参数的函数,以存储对所有正在迭代的所有 i
值的引用,如下所示: / p>
You could wrap your inner setTimeout
call inside a function accepting a parameter in order to store a reference to all the i
values that are being iterated, something like this:
setTimeout(function() {
for (var i = 0; i < 5; i++) {
(function (j) { // added a closure to store a reference to 'i' values
setTimeout(function() {
console.log(j);
}, j * 200);
})(i); // automatically call the function and pass the value
}
}, 200);
有关详细信息,请查看以下问题的答案:
Check my answer to the following question for more details:
- Variables in Anonymous Functions — Can someone explain the following?
这篇关于JavaScript变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!