JavaScript while loop
As long as a specified condition is true, the loop can always execute the code block.
while loop
while true loop will loop code block is executed at the specified conditions.
grammar
{
需要执行的代码
}
Examples
In this case the loop will continue to run as long as the variable i is less than 5:
Examples
{
x=x + "The number is " + i + "<br>";
i++;
}
If you forget to add conditions to the value of the variables used in the cycle never ends. This can cause the browser to crash. |
do / while loop
do / while loop is a variant of the while loop. The cycle will check whether the conditions are true before executing a block of code, and if the condition is true, it will repeat the cycle.
grammar
{
需要执行的代码
}
while ( 条件 );
Examples
The following example uses the do / while loop. The loop will execute at least once, even if the condition is false it will be executed once, because the code block will be executed before the condition is tested:
Examples
{
x=x + "The number is " + i + "<br>";
i++;
}
while (i<5);
Do not forget to increase the value of the variable conditions used, otherwise the cycle will never end!
Compare for and while
If you've read the previous chapter for details about the loop, you will find that while loop like the for loop.
In this example the recycling loop for cars to display all values in the array:
Examples
var i=0;
for (;cars[i];)
{
document.write(cars[i] + "<br>");
i++;
}
In this example of recycling while loop to display all the values in the array of cars:
Examples
var i = 0;
while (cars [i])
{
document.write (cars [i] + "<br>");
i ++;
}