在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