我有一个非常微不足道的问题.对于带有setTimeout的简单循环,如下所示:
for (var count = 0; count < 3; count++) {
setTimeout(function() {
alert("Count = " + count);
}, 1000 * count);
}
Run Code Online (Sandbox Code Playgroud)
console提供如下输出:
Count = 3
Count = 3
Count = 3
Run Code Online (Sandbox Code Playgroud)
不知道为什么输出像这样.有人可以解释一下吗?
这与JavaScript中如何处理范围和提升有关.
您的代码中发生的是JS引擎将您的代码修改为:
var count;
for (count = 0; count < 3; count++) {
setTimeout(function() {
alert("Count = " + count);
}, 1000 * count);
}
Run Code Online (Sandbox Code Playgroud)
并且在setTimeout()运行时它将首先查看它自己的范围,count但它不会找到它然后它将开始查看关闭函数(这称为闭包),setTimeout直到它找到var count语句,这将是具有值3,因为循环将在第一个超时函数执行之前完成.
更多代码解释说您的代码实际上是这样的:
//first iteration
var count = 0; //this is 1 because of count++ in your for loop.
for (count = 0; count < 3; count++) {
setTimeout(function() {
alert("Count = " + 1);
}, 1000 * 1);
}
count = count + 1; //count = 1
//second iteration
var count = 1;
for (count = 0; count < 3; count++) {
setTimeout(function() {
alert("Count = " + 2);
}, 1000 * 2);
}
count = count + 1; //count = 2
//third iteration
var count = 2;
for (count = 0; count < 3; count++) {
setTimeout(function() {
alert("Count = " + 3);
}, 1000 * 3);
}
count = count + 1; //count = 3
//after 1000 ms
window.setTimeout(alert(count));
//after 2000 ms
window.setTimeout(alert(count));
//after 3000 ms
window.setTimeout(alert(count));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2848 次 |
| 最近记录: |