Java教程

无涯教程-Javascript - While循环语句

本文主要是介绍无涯教程-Javascript - While循环语句,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

JavaScript中最基本的循环是 while 循环,本章将对此进行讨论。  while 循环的目的是只要 expression表达式为true,就会执行代码块直至表达式变为 false,循环便终止。

while 流程图

while循环的流程图如下所示:

While loop

JavaScript中 while循环的语法如下-

while (expression) {
   Statement(s) to be executed if expression is 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 LoopCurrent Count : 0Current Count : 1Current Count : 2Current Count : 3Current Count : 4Current Count : 5Current Count : 6Current Count : 7Current Count : 8Current Count : 9Loop stopped!Set the variable to different value and then try...

do ... while 循环类似于 while 循环,除了条件检查发生在循环的末尾。这意味着即使条件为 false ,循环也将至少执行一次。

do ... while 流程图

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

Do While Loop

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

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

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

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 LoopCurrent Count : 0 Current Count : 1 Current Count : 2 Current Count : 3 Current Count : 4Loop Stopped!Set the variable to different value and then try...

参考链接

https://www.learnfk.com/javascript/javascript-while-loop.html

这篇关于无涯教程-Javascript - While循环语句的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!