This article mainly introduces the use of JavaScript while loop, is the basic knowledge of JS learning, need friends can refer to the
When writing a program, there may be a situation when you need to perform some actions over and over again. In such cases, you need to write a looping statement to reduce the number of code.
JavaScript supports all the necessary loops to help you in all programming steps.
While loop
The most basic loop in JavaScript is the while loop, which is discussed in this tutorial.
Grammar
?
1 2 3 |
while (expression) {Statement (s) to was executed if expression is true} |
The while loop is intended to repeatedly execute a statement or block of code (as long as the expression is true). Once an expression is false, the loop is exited.
Example:
The following example illustrates a basic while loop:
?
1 2 3 4 5 6 7 8 9 10 11 |
<script type= "Text/javascript" > <!--var count = 0; document.write ("Starting Loop" + "<br/>"); while (Count < ten) {document.write ("Current count:" + count + "<br/>"); count++; } document.write ("Loop stopped!"); --> </script> |
This will produce the following results:
?
1 2 3 4 5 6 7 8 9 10 11-12 |
Starting Loop current count:0 current count:1 current count:2 current Count:3 current Count:4 current Count:5 Current Count:6 current Count:7 current Count:8 current Count:9 Loop stopped! |
Do...while Cycle:
The Do...while loop is similar to a while loop, except that the conditional check occurs at the end of the loop. This means that the loop will always execute at least once, even if the condition is false.
Grammar
?
1 2 3 |
do{Statement (s) to is executed while (expression); |
Notice that a semicolon is used at the end of the do ... while loop.
Example:
As in the above example, write a use do ... while loop program.
?
1 2 3 4 5 6 7 8 9 10 11 |
<script type= "Text/javascript" > <!--var count = 0; document.write ("Starting Loop" + "<br/>"); do{document.write ("Current count:" + count + "<br/>"); count++; }while (Count < 0); document.write ("Loop stopped!"); --> </script> |
This will produce the following results:
?
|
Starti Ng Loop Current count:0 loop stopped! |