在JavaScript程序中,我有以下两种(简体)函数的对象:For循环“跳到最后”没有明显的原因?
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变为假 - 再次到达
时for (var row=0; row<this.rows; row++)
线,所述row
变量变为立即this.rows
并且因此内循环终止。此外,它发生在外循环的后续运行中 - row
初始化为0
,然后立即变为this.rows
并且内循环再次结束。
我没有理由可以导致这种情况。我试图尽可能地简化功能,并不断发生。
你的第一个nothing_changed是一个局部变量,你的第二个是全局变量 - 是故意的吗? – Ariel
您正在while循环的第一行将'nothing_changed'设置为'true'。这打破了while循环中'nothing_changed'为'false'的情况。 – Utilitron