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

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

技术教程推荐

TensorFlow快速入门与实战 -〔彭靖田〕

趣谈Linux操作系统 -〔刘超〕

移动端自动化测试实战 -〔思寒〕

接口测试入门课 -〔陈磊〕

打造爆款短视频 -〔周维〕

MySQL 必知必会 -〔朱晓峰〕

说透数字化转型 -〔付晓岩〕

快手 · 音视频技术入门课 -〔刘歧〕

结构思考力 · 透过结构看问题解决 -〔李忠秋〕

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