for循环中的函数调用终止循环?

时间:2014-05-02 13:33:44

标签: javascript

我遇到了一个有趣的JavaScript问题。我觉得这可能与闭包有关,我承认,我不太满意。

问题 似乎从内部调用函数会导致循环过早终止。我尝试在没有函数调用的情况下运行相同的循环,并且console.log()输出计数器,准确地表明函数调用正在打破循环。

有人会建议可能的修复吗?我把代码粘贴在这里:

AbstractModel.prototype.deactivateContext   = function(context){

  for(i=0;i<this.asset.length;i++){
      if(this.asset[i].context == context){
        this.asset[i].deactivate();
        console.log(i);
        this.notify(this.asset[i],"REFRESHASSETS");
      }
  }
}

3 个答案:

答案 0 :(得分:5)

var不是可选的

您可能在另一种方法中拥有全局i。将变量声明为正确的范围。

for (var i=0; i<this.asset.length; i++) {
     ^^^

答案 1 :(得分:3)

请在以下功能中声明我,例如

AbstractModel.prototype.deactivateContext   = function(context){

  for(var i=0;i<this.asset.length;i++){
      if(this.asset[i].context == context){
        this.asset[i].deactivate();
        console.log(i);
        this.notify(this.asset[i],"REFRESHASSETS");
      }
  }
}

看起来我在通知函数中被修改为更高的数字,当它从通知返回时for检查正在退出。

答案 2 :(得分:1)

您是否尝试将调用包装到try catch中的notify函数中。如果您在删除呼叫时说,计数器的输出按预期打印,那么唯一的解释是您的函数抛出异常。试试这个:

 for(i=0;i<this.asset.length;i++){
      if(this.asset[i].context == context){
        this.asset[i].deactivate();
        console.log(i);
        try {
          this.notify(this.asset[i],"REFRESHASSETS");
        } catch(e) {
           alert(e);
           console.log(e);
        }
      }
  }
相关问题