【问题标题】:Passing array and index within `for` loop and `setTimeout()` [duplicate]在`for`循环和`setTimeout()`中传递数组和索引[重复]
【发布时间】:2016-01-12 09:27:22
【问题描述】:

我想在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);
}

谁能解释一下为什么会这样以及如何正确传递数组和索引?

谢谢, 丹

【问题讨论】:

  • 这是因为在执行 IIFE 时,i 的值已更改为 templates.length
  • 这是一个范围问题。一旦超时触发,i 将不再在范围内。
  • 所以应该是for (var i = 0; i &lt; templates.length; i++) { (function(i, templates) { setTimeout(function() { templates[i].click(); }, 200); }(i, templates)); }
  • 谢谢大家。通过传递一个在那个时刻肯定是相同的值来解决。 for(var i=0; i&lt;templates.length; i++){ setTimeout(function(){ (function(){ templates[templates_arr.length].click(); }(templates)); }, 200); setTimeout(function(){ (function(){ templates_arr.push(htmlDecode(mainwindow.document.getElementById('XmlFrame').contentDocument.getElementById('id_1').innerHTML)); }(templates_arr, templates)); }, 200); }
  • @JohannesJander 你正在创建多个函数实例,你可以使用var func = function(template) { setTimeout(function() { template.click(); }, 200); }; for (var i = 0; i &lt; templates.length; i++) { func(templates[i]); } 解决它

标签: javascript arrays for-loop settimeout self-invoking-function


【解决方案1】:

应该是

for(var i=0; i<templates.length; i++){
   (function(i,templates){
       setTimeout(function(){
            templates[i].click();
       }, 200);
   })(i, templates);

}

【讨论】:

    猜你喜欢
    • 2018-04-26
    • 2014-05-18
    • 2020-11-20
    • 1970-01-01
    • 2011-09-27
    • 2016-08-30
    • 1970-01-01
    • 2013-01-25
    • 1970-01-01
    相关资源
    最近更新 更多