Loop a code block as long as a i is less than 5:
let text = "";
let i = 0;
while (i < 5) {
text += i + "<br>";
i++;
}
Try it Yourself »
Loop (iterate over) an array to collect car names:
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let text = "";
let i = 0;
while (i < cars.length) {
text += cars[i] + "<br>";
i++;
}
Try it Yourself »
let i = 0
).i
for each run (i++
).i < cars.length
.More examples below.
The while
statement creates a loop (araund a code block) that is executed while a condition is true
.
The loop runs while the condition is true
. Otherwise it stops.
Statement | Description | |
break | Breaks out of a loop | |
continue | Skips a value in a loop | |
while | Loops a code block while a condition is true | |
do...while | Loops a code block once, and then while a condition is true | |
for | Loops a code block while a condition is true | |
for...of | Loops the values of any iterable | |
for...in | Loops the properties of an object |
while (condition) {
code block to be executed
}
Parameter | Description |
condition | Required. The condition for running the code block. If it returns true, the code clock will start over again, otherwise it ends. |
If the condition is always true, the loop will never end. This will crash your browser.
If you use a variable in the condition, you must initialize it before the loop, and increment it within the loop. Otherwise the loop will never end. This will also crash your browser.
Loop over an array in descending order (negative increment):
const cars = ["BMW", "Volvo", "Saab", "Ford"];
let text = "";
let len = cars.length;
while (len--) {
text += cars[len] + "<br>";
}
Try it Yourself »
Using break - Loop through a block of code, but exit the loop when i == 3:
let text = "";
let i = 0;
while (i < 5) {
text += i + "<br>";
i++;
if (i == 3) break;
}
Try it Yourself »
Using continue - Loop through a block of code, but skip the value 3:
let text = "";
let i = 0;
while (i < 5) {
i++;
if (i == 3) continue;
text += i + "<br>";
}
Try it Yourself »
while
is an ECMAScript1 (ES1) feature.
ES1 (JavaScript 1997) is fully supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |
截取页面反馈部分,让我们更快修复内容!也可以直接跳过填写反馈内容!