在 Javascript 程序中,我有一个具有以下两个(简化的)函数的对象:
this.do_A = function() {
var nothing_changed = false;
while (!nothing_changed) {
nothing_changed = true;
for (var column=0; column<this.columns; column++) {
for (var row=0; row<this.rows; row++) {
nothing_changed = nothing_changed && this.do_B(row, column);
}
}
}
}
this.do_B = function(row, column) {
nothing_changed = true;
if (this[row][column] == null) {
nothing_changed = false;
}
return nothing_changed;
}
运行此代码时,do_B 返回 false 时会发生一些非常奇怪的事情,因此 nothing_changed 变为 false - 当再次到达
for (var row=0; row<this.rows; row++)
行,row
变量立即变为 this.rows
,因此内部循环终止。此外,它发生在外层循环的后续运行中 - row
被初始化为 0
,然后立即变为 this.rows
并且内层循环再次结束。
我不知道是什么原因造成的。我已经尝试尽可能地简化功能,而且这种情况一直在发生。
最佳答案
for (var row=0; row<this.rows; row++)
{
nothing_changed = nothing_changed && this.do_B(row, column);
}
当 this.do_B(row, column)
返回 false
时,nothing_changed
将为 false
, 当再次循环到达nothing_changed = nothing_changed && this.do_B(row, column)
时,因为nothing_changed
为false
,第二个表达式this.do_B(row, column)
将不会被评估,因此 nothing_changed
将始终为 false
直到 row
到达this.rows
.
关于javascript - 对于没有明显原因的循环 "jumps to the end"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6762053/