更新时间:2021-08-24 03:10:44
这是经常重复的如何在闭包问题中使用循环变量。
This is the very frequently repeated "how do I use a loop variable in a closure" problem.
规范的解决方案是调用一个函数,该函数返回一个绑定到循环变量当前值的函数:
The canonical solution is to call a function which returns a function that's bound to the current value of the loop variable:
var strings = [ "hello", "world" ];
var delay = 1000;
for(var i=0;i<strings.length;i++) {
setTimeout(
(function(s) {
return function() {
alert(s);
}
})(strings[i]), delay);
delay += 1000;
}
外部定义 function(s){.. 。}
创建一个新范围,其中 s
绑定到所提供参数的当前值 - 即 strings [i]
- 内部范围可用的地方。
The outer definition function(s) { ... }
creates a new scope where s
is bound to the current value of the supplied parameter - i.e. strings[i]
- where it's available to the inner scope.