繁体   English   中英

For 循环无缘无故“跳到最后”?

[英]For loop “jumps to the end” for no apparent reason?

在 Javascript 程序中,我有一个 object 具有以下两个(简化)功能:

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

你怎么知道for循环跳到最后? 如果您通过搜索do_B的调用进行检查,那么您需要考虑以下表达式中的事实:

nothing_changed && this.do_B(row, column)

如果nothing_changed已经是false ,那么this.do_B(row, column)将不会被调用,因为无论 RHS 计算什么,整个表达式都会计算为false

这称为短路

也许这就是正在发生的事情? 如果您将 debug output 直接放在for循环中,我相信您会看到它继续到规定的迭代次数结束:

for (var column=0; column<this.columns; column++) {
  for (var row=0; row<this.rows; row++) {
    console.log(column + "|" + row);
    nothing_changed = nothing_changed && this.do_B(row, column);
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM