分享

前端教程:JavaScript while循环

 码农9527 2021-08-19

在写一个程序时,可能有一种情况,当你需要一遍又一遍的执行一些操作。在这样的情况下,则需要写循环语句,以减少代码的数量。  

前端教程:JavaScriptwhile循环

JavaScript支持所有必要的循环,以帮助您在所有编程的步骤。  

while 循环  

在JavaScript中最基本的循环是while循环,这将在本教程中学习讨论。  

语法  

while (expression){
   Statement(s) to be executed if expression is true}123复制代码类型:[javascript]

while循环的目的是为了反复执行语句或代码块(只要表达式为true)。一旦表达式为假,则循环将被退出。  

例子:  

下面的例子说明了一个基本的while循环:  

<script type="text/javascript">
<!--var count = 0;document.write("Starting Loop" + "<br />");while (count < 10){  document.write("Current Count : " + count + "<br />");
  count++;
}document.write("Loop stopped!");//--></script>12345678910111213复制代码类型:[javascript]

这将产生以下结果:  

Starting Loop
Current Count : 0Current Count : 1Current Count : 2Current Count : 3Current Count : 4Current Count : 5Current Count : 6Current Count : 7Current Count : 8Current Count : 9Loop stopped!1234567891011121314复制代码类型:[javascript]

do...while 循环:  

do...whileloop类似于while循环,不同之处在于条件检查发生在循环的末端。这意味着,在循环将总是至少执行一次,即使条件为假。  

语法  

do{
   Statement(s) to be executed;
} while (expression);123复制代码类型:[javascript]

注意在do...while循环的末尾使用分号。  

例子:  

如在上面的例子中编写一个使用do...while循环程序。  

<script type="text/javascript">
<!--var count = 0;document.write("Starting Loop" + "<br />");do{  document.write("Current Count : " + count + "<br />");
  count++;
}while (count < 0);document.write("Loop stopped!");//--></script>12345678910111213复制代码类型:[javascript]

这将产生以下结果:  

Starting Loop
Current Count : 0Loop stopped!

    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多