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
语法
示例
使用 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.
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:
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 |
浏览器兼容性
BCD tables only load in the browser