do...while

do...while

do...while语句创建一个执行指定语句的循环,直到condition值为 false。在执行statement后检测condition,所以指定的statement至少执行一次。

语法

do statement while (condition

statement执行至少一次的语句,并在每次condition值为真时重新执行。想执行多行语句,可使用block语句({ ... })包裹这些语句。condition循环中每次都会计算的表达式。如果condition值为真,statement会再次执行。当condition值为假,则跳到do...while之后的语句。

示例

使用 do...while

下面的例子中,do...while 循环至少迭代一次,并且继续迭代直到i不再小于 5 时结束。

HTML 内容

<div id="example"></div>

JavaScript 内容

var result = ''; var i = 0; do {    i += 1;    result += i + ' '; } while (i < 5 document.getElementById('example').innerHTML = result;

结果

规范

SpecificationStatusComment
ECMAScript 3rd Edition (ECMA-262)StandardInitial definition. Implemented in JavaScript 1.2
ECMAScript 5.1 (ECMA-262)The definition of 'do-while statement' in that specification.Standard
ECMAScript 2015 (6th Edition, ECMA-262)The definition of 'do-while statement' in that specification.StandardTrailing ; is now optional.
ECMAScript Latest Draft (ECMA-262)The definition of 'do-while statement' in that specification.Living Standard

浏览器兼容性

FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support(Yes)(Yes)(Yes)6(Yes)(Yes)

FeatureAndroidChrome for AndroidEdgeFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Basic support(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)(Yes)