while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.
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
is executed. When condition evaluates to false, execution continues with the statement after the
while
loop.
statement
{ ... }
) to group those statements.
break
statement to stop a loop before condition evaluates to true.
下列
while
loop iterates as long as
n
is less than three.
var n = 0;
var x = 0;
while (n < 3) {
n++;
x += n;
}
Each iteration, the loop increments
n
and adds it to
x
. Therefore,
x
and
n
take on the following values:
n
= 1 and
x
= 1
n
= 2 and
x
= 3
n
= 3 and
x
= 6
After completing the third pass, the condition
n
< 3 is no longer true, so the loop terminates.
| 规范 |
|---|
|
ECMAScript (ECMA-262)
The definition of 'while statement' in that specification. |
| Desktop | Mobile | Server | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
while
|
Chrome 1 | Edge 12 | Firefox 1 | IE 3 | Opera 3 | Safari 1 | WebView Android 1 | Chrome Android 18 | Firefox Android 4 | Opera Android 10.1 | Safari iOS 1 | Samsung Internet Android 1.0 | nodejs 0.1.100 |
完整支持