while (条件) { 需要执行的代码; }
while
#The for loop is very useful when the initial and end conditions of the loop are known. The above for loop that ignores conditions can easily make people unclear about the logic of the loop. In this case, it is better to use a while loop.
The while loop has only one judgment condition. If the condition is met, it will continue to loop. If the condition is not met, it will exit the loop. For example, if we want to calculate the sum of all odd numbers within 100, we can use a while loop to implement it:
var x = 0; var n = 99; while (n > 0) { x = x + n; n = n - 2; } x; // 2500
The variable n inside the loop continues to decrement until it becomes -1, the while condition is no longer satisfied, and the loop exits.
Example
<!DOCTYPE html> <html> <body> <p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction() { var x="",i=0; while (i<5) { x=x + "The number is " + i + "<br>"; i++; } document.getElementById("demo").innerHTML=x; } </script> </body> </html>
do ... while
The last type of loop is the do { ... } while() loop. The only difference between it and the while loop is that the condition is not judged at the beginning of each loop. Instead, the condition is judged when each loop is completed:
var n = 0; do { n = n + 1; } while (n < 100); n; // 100
Be careful when using do { ... } while() loop. The loop body will be executed at least once, while the for and while loops may not be executed once. implement.
Example
<!DOCTYPE html> <html> <body> <p>点击下面的按钮,只要 i 小于 5 就一直循环代码块。</p> <button onclick="myFunction()">点击这里</button> <p id="demo"></p> <script> function myFunction() { var x="",i=0; do { x=x + "The number is " + i + "<br>"; i++; } while (i<5) document.getElementById("demo").innerHTML=x; } </script> </body> </html>