怎么算到3?

时间:2010-10-28 01:55:00

标签: javascript

  

可能重复:
  Javascript closure inside loops - simple practical example
  Javascript closure “stores” value at the wrong time

for (var i = 1; i <= 3; ++i) {
    setTimeout(function() {
        alert(i);
    }, i * 1000);
}

此警报“4”3次。我知道为什么,但我不会在这里破坏它......虽然我忘记了如何解决它。什么是解决这个问题的简洁方法?

2 个答案:

答案 0 :(得分:5)

for (var i = 1; i <= 3; ++i) {
    setTimeout((function (x) {
        return function () { alert(x); }
    })(i), i * 1000);
}

答案 1 :(得分:4)

这是一个非常普遍的问题。 With JS 1.7 this is easily solved using let keyword。要查看browser version equivalency click here

您可以使用闭包解决此问题。为i创建范围并返回setTimeout的函数。

for (var i = 1; i <= 3; ++i) {
    setTimeout((function(i) { /* i is now a parameter */
        return function () { /* this function is the one that will execute */
            alert(i); /* this `i` is not the same as the one used on the loop */
        }
    })(i), i * 1000);
}