【问题标题】:Why is this do-while loop in infinite?为什么这个 do-while 循环是无限的?
【发布时间】:2016-07-14 10:37:57
【问题描述】:

我正在学习 do-while 循环,但无法理解为什么这个循环会无限运行。

 var condition = true

 var getToDaChoppa = function(){

      do {
          console.log("I'm the do loop");
      } while(condition === true){
          console.log("I'm the while loop");
          condition = false;
      };

    };

 getToDaChoppa();

【问题讨论】:

  • 循环以do 开始,以while 结束,中间没有任何改变condition。它后面的块只是一个单独的块。

标签: javascript loops while-loop do-while


【解决方案1】:

您永远不会将 condition 变量设置为 false INSIDE 循环,因此它永远不会在循环之外执行任何代码,直到循环完成(这永远不会发生给定您当前的示例)。确保在循环内将condition 变量设置为false

do {
    console.log("I'm the do loop");

    if (some_condition_is_met) {
        condition = false;
    }
} while(condition === true);

【讨论】:

  • 嗨达林,我刚刚意识到错误!能否给出改进后的答案,我以后会为用户接受答案?
【解决方案2】:

Do/While 像这样工作。所以你永远不会改变循环内的condition

do {
    //code block to be executed
}
while (condition);

//Code after do/while

【讨论】:

  • 那么'while'循环中的位有什么作用呢?有没有检查条件是否满足?
  • 你基本上可以在里面做任何事情。管理一个柜台或类似的东西。您只需要确保迟早将condition 设置为false,否则它将永远不会结束。
【解决方案3】:

有一个do..while,有一个while..没有do..while..声明

JavaScript 允许 block statements 独立于其他流控制/定义结构。由于缺少必需的语句分号,这不会导致语法错误(在 Java 中会)。

这里有一些关于语法的额外说明;其他答案涵盖了逻辑错误。

do {
    console.log("I'm the do loop");
} while(condition === true) // semicolons optional in JS (see ASI):
                            // 'do..while' statement ENDS HERE
{  // starts a block statement which has naught to do with 'do..while' above
   // THERE IS NO WHILE LOOP HERE
    console.log("I'm the while loop");
    condition = false;
}; // useless semicolon which further leads to confusion

另一方面,如果 do.. 被省略,它将被解析为“只是”一个 while 语句,该语句将终止。

// Basic WHILE statement - no 'do..' code, so NOT parsed as a 'do..while'!
while(condition === true)
{  // this block is now part of the 'while' statement loop
    console.log("I'm the while loop");
    condition = false;
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 2018-03-17
    • 2011-11-15
    • 2012-11-01
    • 1970-01-01
    • 2016-05-26
    • 2016-07-27
    相关资源
    最近更新 更多