在 `for` 循环和 `setTimeout()` 中传递数组和索引
Passing array and index within `for` loop and `setTimeout()`
我想在 for
循环中 setTimeout
中点击 templates[i]
for(var i=0; i<templates.length; i++){
setTimeout(function(){
(function(){
templates[i].click();
}(i, templates));
}, 200);
}
我收到错误 templates[i]
未定义。
然而,像这样的东西工作正常:
for(var i=0; i<templates.length; i++){
setTimeout(function(){
(function(){
console.log(templates_arr+templates)
}(templates_arr, templates));
}, 200);
}
谁能解释一下为什么会这样,以及我如何正确传递数组和索引?
谢谢,
旦
应该是
for(var i=0; i<templates.length; i++){
(function(i,templates){
setTimeout(function(){
templates[i].click();
}, 200);
})(i, templates);
}
我想在 for
循环中 setTimeout
中点击 templates[i]
for(var i=0; i<templates.length; i++){
setTimeout(function(){
(function(){
templates[i].click();
}(i, templates));
}, 200);
}
我收到错误 templates[i]
未定义。
然而,像这样的东西工作正常:
for(var i=0; i<templates.length; i++){
setTimeout(function(){
(function(){
console.log(templates_arr+templates)
}(templates_arr, templates));
}, 200);
}
谁能解释一下为什么会这样,以及我如何正确传递数组和索引?
谢谢, 旦
应该是
for(var i=0; i<templates.length; i++){
(function(i,templates){
setTimeout(function(){
templates[i].click();
}, 200);
})(i, templates);
}