我有一个 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/