目录

Javascript - While 循环

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

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

while循环

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

流程图

while loop流程图如下 -

循环

语法 (Syntax)

JavaScript中while loop的语法如下 -

while (expression){
   Statement(s) to be executed if expression is true
}

例子 (Example)

请尝试以下示例来实现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>

输出 (Output)

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... 

做... while循环

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

流程图

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

做循环

语法 (Syntax)

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

do{
   Statement(s) to be executed;
} while (expression);

Note - 不要错过do ... while循环结束时使用的分号。

例子 (Example)

请尝试以下示例,以了解如何在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>

输出 (Output)

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...
↑回到顶部↑
WIKI教程 @2018