Javascript For 循环被函数调用中断?

标签 javascript loops for-loop

我有一个 for 循环,它在没有完成循环的情况下终止。这似乎与循环内是否调用另一个函数有关。

this.cycle = function() {
    var list = this.getBreaches("Uncontained");
    if (list.length > 0) {
        for (i=0; i < list.length; i++) {
           this.saveVsRupture(DC=11, i);   //calls this.rupture() if save failed
    }}
    return 1;
};

this.saveVsRupture() 调用一个滚动 d20 并检查结果的函数。如果保存失败,它会调用一个名为 this.rupture() 的方法来对此进行一些调整。

问题 如果保存抛出成功,则循环继续,但如果保存抛出失败,则运行 this.rupture() 函数,然后中断 for 循环。它应该继续运行 for 循环。

为什么会发生这种情况?

其他详细信息 这是其他功能...

    savingThrow = function(DC=11) {
    // DC = Difficulty Check on a d20   
    try {
        if (0 <= DC) {      
            var roll = Math.floor((Math.random() * 20))+1;  //roll d20
            var msg = "(Rolled "+roll+" vs DC "+DC+")";
            console.log(msg);       
            if (roll >= DC) {   //Saved
                return true;
            }
            else {  //Failed save
                return false;
            }
        }
    }
    catch(e) {
        console.log("Exception in savingThrow: "+e);        
    };
  };

    this.saveVsRupture = function(DC=1, i=null) {
    try {
        if (!savingThrow(DC)) {
            this.rupture(i);
            return false;
        }
        return true;
    }
    catch(e) {
        console.log(e);         
        }   
};


    this.rupture = function(i=null) {
    if (i == null) {
        i = range(1,this.damageList.length).sample();       
    }
    var hole = this.damageList[i];
    var dmg = range(1,this.harmonics()).sample();
    hole.rupture(dmg);
    msg = "*ALERT* " + hole + " expanded by " + dmg + "% Hull Integrity @"+this.hullIntegrity();
    this.log(msg);
    if (hole.size % 10 == 0) {
        this.health -= 25;
        msg = "The ship creaks ominously.";
        this.log(msg); 
    }
    return 1;
};  

最佳答案

for 循环的正确语法声明计数器变量。

    for (var i=0; i < list.length; i++) {etc..

    /// Causes the For-Loop to exit prematurely...
    for (i=0; i < list.length; i++) {etc..

一旦使用“var i=0”,for循环就会按预期运行。

关于Javascript For 循环被函数调用中断?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34114310/

相关文章:

bash - 如何遍历目录中的所有文件,按创建日期排序,有些文件名的名称中有空格

java - 循环 jtextfields,以便清除是否输入了除整数之外的任何内容

c - 指针递增与指针递增

javascript - 如何在wordpress导航菜单上添加javascript

javascript - 来自coffeescript.org示例的拼接逻辑

java - 文件 io 搜索直到匹配 java

algorithm - 计算循环的运行时间

python - 删除 Pandas Dataframe 列范围内每列总和小于 10 的列

javascript - 如何在jquery中选择上一个元素?

javascript - 在 ng-repeat 中使用 ng-disabled