为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
JavaScript

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

点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消