JavaScript中最基本的循环是 while 循环,本章将对此进行讨论。 while 循环的目的是只要 expression表达式为true,就会执行代码块直至表达式变为 false,循环便终止。
while 流程图
while循环的流程图如下所示:
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 循环的流程图如下-
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