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
回调函数是异步执行的,您所做的所有 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
值的引用,如下所示:
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:
这篇关于JavaScript 变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!