JavaScript - 循环

编写程序时,您可能会遇到需要反复执行操作的情况。在这种情况下,你需要编写循环语句来减少行数。

JavaScript支持所有必要的循环来减轻编程压力。

while循环

JavaScript中最基本的循环是 while 循环,本章将对此进行讨论。 while 循环的目的是重复执行语句或代码块,只要表达式为真。表达式变为 false后,循环终止。

流程图

while循环的流程图看起来如下 :

while loop

语法

JavaScript中 while loop 的语法如下 :

while(expression){
    表达式为true时要执行的语句
}


示例

尝试以下示例来实现while循环。

在线演示

<html>
   <body>
      
      <script type = "text/javascript">
         <!--
            var count = 0;
            document.write("Starting Loop ");
         
            while (count < 10) {
               document.write("Current Count : " + count + "<br />");
               count++;
            }
         
            document.write("Loop stopped!");
         //-->
      </script>
      
      <p>Set the variable to different value and then try...</p>
   </body>
</html>


输出

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!
Set the variable to different value and then try...


do ... while循环

do ... while 循环类似于 while 循环,只是条件检查发生在循环结束时。这意味着循环将始终至少执行一次,即使条件为 false

流程图

do-while 循环的流程图如下:<

Do While Loop

语法

JavaScript中 do-while 循环的语法如下 :

do {
    要执行的声明; 
} while(expression);


注意 : 不要错过 do ... while 循环结束时使用的分号。

示例

尝试以下示例了解如何在JavaScript中实现 do-while 循环。

在线演示

<html>
   <body>   
      <script type = "text/javascript">
         <!--
            var count = 0;
            
            document.write("Starting Loop" + "<br />");
            do {
               document.write("Current Count : " + count + "<br />");
               count++;
            }
            
            while (count < 5);
            document.write ("Loop stopped!");
         //-->
      </script>      
      <p>Set the variable to different value and then try...</p>
   </body>
</html>


输出

Starting Loop
Current Count : 0 
Current Count : 1 
Current Count : 2 
Current Count : 3 
Current Count : 4
Loop Stopped!
Set the variable to different value and then try...