javascript - 对于没有明显原因的循环 "jumps to the end"?

标签 javascript for-loop

在 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_changedfalse,第二个表达式this.do_B(row, column) 将不会被评估,因此 nothing_changed 将始终为 false 直到 row 到达this.rows.

关于javascript - 对于没有明显原因的循环 "jumps to the end"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6762053/

相关文章:

javascript - Angular 2 匹配/合并/推送和更新 Json

javascript - 对象字面量语法奇怪

for-loop - F# for 循环错误

Python JSON try except block 不起作用

c# - foreach 循环内的 LINQ 表达式

javascript - 是否有另一种方法可以在此函数之外关闭 MongoDB 连接?

javascript - 在 Angular 中将图像转换为文件类型

javascript - 为 Twitter Bootstrap 更新日期范围选择器的选定日期

C# for 循环计数数组不工作

c - For循环在C中崩溃