do...while

do...while 语句创建一个循环,该循环执行指定的语句,直到测试条件的计算结果为 false。执行语句后评估条件,导致指定的语句至少执行一次。

¥The do...while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.

Try it

语法

¥Syntax

js
do
  statement
while (condition);
statement

至少执行一次的语句,每次条件评估为 true 时都会重新执行。要在循环内执行多个语句,请使用 block 语句 ({ /* ... */ }) 对这些语句进行分组。

condition

每次循环后计算的表达式。如果 condition 评估结果为真,则重新执行 statement。当 condition 评估结果为假 时,控制权传递到 do...while 之后的语句。

注意:使用 break 语句在 condition 计算结果为 false 之前停止循环。

示例

¥Examples

使用 do...while

¥Using do...while

在以下示例中,do...while 循环至少迭代一次并重复,直到 i 不再小于 5。

¥In the following example, the do...while loop iterates at least once and reiterates until i is no longer less than 5.

js
let result = "";
let i = 0;
do {
  i += 1;
  result += `${i} `;
} while (i > 0 && i < 5);
// Despite i === 0 this will still loop as it starts off without the test

console.log(result);

使用赋值作为条件

¥Using an assignment as a condition

在某些情况下,使用赋值作为条件是有意义的,例如:

¥In some cases, it can make sense to use an assignment as a condition, such as this:

js
do {
  // …
} while ((match = regexp.exec(str)));

但当你这样做时,就需要牺牲可读性。while 文档有一个 使用赋值作为条件 部分,其中包含我们的建议。

¥But when you do, there are readability tradeoffs. The while documentation has a Using an assignment as a condition section with our recommendations.

规范

Specification
ECMAScript Language Specification
# sec-do-while-statement

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看

¥See also