--- title: do...while slug: Web/JavaScript/Reference/Statements/do...while tags: - JavaScript - Statement translation_of: Web/JavaScript/Reference/Statements/do...while ---
do...while
语句创建一个执行指定语句的循环,直到condition
值为 false。在执行statement
后检测condition
,所以指定的statement
至少执行一次。
do statement while (condition);
statement
condition
值为真时重新执行。想执行多行语句,可使用{{jsxref("Statements/block", "block")}}语句({ ... }
)包裹这些语句。condition
condition
值为真, statement
会再次执行。当 condition
值为假,则跳到do...while
之后的语句。do...while
下面的例子中,do...while
循环至少迭代一次,并且继续迭代直到 i
不再小于 5 时结束。
<div id="example"></div>
var result = ''; var i = 0; do { i += 1; result += i + ' '; } while (i < 5); document.getElementById('example').innerHTML = result;
{{ EmbedLiveSample('Examples') }}
Specification | Status | Comment |
---|---|---|
{{SpecName('ES3')}} | {{Spec2('ES3')}} | Initial definition. Implemented in JavaScript 1.2 |
{{SpecName('ES5.1', '#sec-12.6.1', 'do-while statement')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES6', '#sec-do-while-statement', 'do-while statement')}} | {{Spec2('ES6')}} | Trailing ; is now optional. |
{{SpecName('ESDraft', '#sec-do-while-statement', 'do-while statement')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.statements.do_while")}}