Javascript - While循环语句

Javascript - While循环语句 首页 / JavaScript入门教程 / 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 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 循环类似于 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 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...

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

朱赟的技术管理课 -〔朱赟〕

Go语言核心36讲 -〔郝林〕

技术管理实战36讲 -〔刘建国〕

研发效率破局之道 -〔葛俊〕

如何看懂一幅画 -〔罗桂霞〕

动态规划面试宝典 -〔卢誉声〕

Python自动化办公实战课 -〔尹会生〕

超级访谈:对话张雪峰 -〔张雪峰〕

JavaScript进阶实战课 -〔石川〕

好记忆不如烂笔头。留下您的足迹吧 :)