var funcs = [];
// let's create 3 functions
for (var i = 0; i < 3; i++) {
// and store them in funcs
funcs[i] = function() {
// each should log its value.
console.log("My value: " + i);
};
}
for (var j = 0; j < 3; j++) {
// and now let's run each one to see
funcs[j]();
}Run Code Online (Sandbox Code Playgroud)
它输出这个:
我的价值:3
我的价值:3
我的价值:3
而我希望它输出:
我的价值:0
我的价值:1
我的价值:2
使用事件侦听器导致运行函数的延迟时,会出现同样的问题:
var buttons = document.getElementsByTagName("button");
// let's create 3 …Run Code Online (Sandbox Code Playgroud)考虑这样的循环:
for(var it = 0; it < 2; it++)
{
setTimeout(function() {
alert(it);
}, 1);
}
Run Code Online (Sandbox Code Playgroud)
输出是:
=> 2
=> 2
Run Code Online (Sandbox Code Playgroud)
我希望它是:0,1.我看到两种方法来解决它:
解决方案#1.
这个基于我们可以将数据传递给setTimeout的事实.
for(var it = 0; it < 2; it++)
{
setTimeout(function(data) {
alert(data);
}, 1, it);
}
Run Code Online (Sandbox Code Playgroud)
解决方案#2.
function foo(data)
{
setTimeout(function() {
alert(data);
}, 1);
}
for(var it = 0; it < 2; it++)
{
foo(it);
}
Run Code Online (Sandbox Code Playgroud)
还有其他选择吗?