while 语句可以在某个条件表达式为真的前提下,循环执行指定的一段代码,直到那个表达式不为真时结束循环。
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.
语法
while (condition) statement
-
condition
-
条件表达式,在每次循环前被求值。如果求值为真,
statement
就会被执行。如果求值为假,则跳出while
循环执行后面的语句。 -
statement
-
只要条件表达式求值为真,该语句就会一直被执行。要在循环中执行多条语句,可以使用块语句(
{ ... }
)包住多条语句。 -
注意:使用
break
语句在condition
计算结果为真之前停止循环。
示例
下面的 while
循环会一直循环若干次,直到 n
等于 3
。
var n = 0; var x = 0; while (n < 3) { n++; x += n; }
在每次循环中,n
都会自增 1
,然后再把 n
加到 x
上。因此,在每轮循环结束后,x
和 n
的值分别是:
- 第一轮后:
n
= 1,x
= 1 - 第二轮后:
n
= 2,x
= 3 - 第三轮后:
n
= 3,x
= 6
当完成第三轮循环后,条件表达式n
< 3 不再为真,因此循环终止。
规范
规范 | 状态 | 备注 |
---|---|---|
ECMAScript Latest Draft (ECMA-262) while statement |
Draft | |
ECMAScript 2015 (6th Edition, ECMA-262) while statement |
Standard | |
ECMAScript 5.1 (ECMA-262) while statement |
Standard | |
ECMAScript 3rd Edition (ECMA-262) while statement |
Standard | |
ECMAScript 1st Edition (ECMA-262) while statement |
Standard | Initial definition |
浏览器兼容性
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out
https://github.com/mdn/browser-compat-data and send us a pull request.
Update compatibility data on GitHub
Desktop | Mobile | Server | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
while |
Chrome Full support 1 | Edge Full support 12 | Firefox Full support 1 | IE Full support 3 | Opera Full support Yes | Safari Full support Yes | WebView Android Full support 1 | Chrome Android Full support 18 | Firefox Android Full support 4 | Opera Android Full support Yes | Safari iOS Full support Yes | Samsung Internet Android Full support 1.0 | nodejs Full support Yes |
Legend
- Full support
- Full support