`w

`while`循环 属于 JavaScript

8 个练习

关于 `while`循环

一般语法

使用while循环,只要满足某个条件,就能重复运行代码。

它的写法是先写while关键字,后面跟一个用圆括号括起来的条件,再跟一个用大括号括起来的代码块,其中包含循环的_循环体_。

while (condition) {
  // code that is executed repeatedly as long as the condition is
  // true
}

JavaScript 还有 do-while 循环。这种循环在执行完循环体之后才检查条件。当条件取决于循环体中所做的求值结果时,这很有用。

do {
  // The code here will always be executed once and then
  // repeatedly while the condition is true.
} while (condition);

break 关键字

在循环体中,你可以使用break关键字彻底停止循环的执行。它常与true搭配使用,也就是把条件写成true。这样,你就可以在循环体内部的任何位置控制循环何时停止。

const winningNumber = 7;

while (true) {
  const num = readUserGuess();
  if (num === winningNumber) {
    break;
  }
}

break关键字不能用在嵌套于该循环中的函数里,示例见 MDN 文档。

continue 关键字

与break不同,continue关键字只停止当前这一次迭代的执行,然后继续下一次迭代。借助continue,你常常可以避免把循环体的大部分代码包进if语句里。

let i = 0;

while (i < 100) {
  i = i + 2;

  if (i % 3 === 0) {
    continue;
  }

  // The code here will only be executed when i was not divisible
  // by 3 in the check above.
}

无限循环

当循环条件始终满足,并且循环体中永远不会执行到 break 或 return 语句时,就会产生一个(理论上)永远重复的循环。执行必须从外部终止。取决于这类代码运行的环境,终止可能是自动完成的,也可能需要手动干预。

let i = 0;

while (i < 100) {
  if (i % 3 === 0) {
    continue;
  }

  i = i + 2;
}

// This loop runs forever since the variable i does not change
// anymore after it is divisible by 3 the first time.

在这个小示例里,发现无限循环也许看起来很简单,但在更复杂的代码中并不总是那么容易。养成好习惯:认真想清楚你的条件最终是否会变成 false,以及你的 break 或 return 语句是否会被执行到。

通过 GitHub 编辑 该链接会在新窗口或标签页中打开

学习 `while`循环