编写程序时,您可能会遇到需要反复执行操作的情况。在这种情况下,你需要编写循环语句来减少行数。
JavaScript支持所有必要的循环来减轻编程压力。
JavaScript中最基本的循环是 while 循环,本章将对此进行讨论。 while 循环的目的是重复执行语句或代码块,只要表达式为真。表达式变为 false后,循环终止。
while循环的流程图看起来如下 :
JavaScript中 while loop 的语法如下 :
while(expression){ 表达式为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 循环的流程图如下:<
JavaScript中 do-while 循环的语法如下 :
do { 要执行的声明; } while(expression);
注意 : 不要错过 do ... while 循环结束时使用的分号。
尝试以下示例了解如何在JavaScript中实现 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...