JavaScript While循环语句
Posted by 撒得一地 on 2016年5月4日 in JavaScript教程
在写一个程序,你可能会遇到需要反复执行某项操作的情况。在这种情况下,你需要编写循环语句来减少重复的操作语句。
JavaScript 支持循环操作,循环操作减少了编程压力。
While 循环
在 JavaScript 中的最基本的循环是 while 循环,该循环将在下面进行讨论。循环的目的是,只要一个表达式为 true,便在一段时间内循环重复执行一个语句或代码块。一旦该表达式为假,则循环就会终止。
流程图
While 循环流程图如下:
语法
While 循环在 JavaScript 中的语法,如下所示:
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>
Output 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 循环
do…while 循环类似 while 循环,只是 do…while 循环条件检查发生在循环结束后。这意味着 do…while 至少执行一次循环,即使执行循环的条件为 false。
流程图
do…while 循环流程图如下:
语法
在 JavaScript 中 do…while 循环的语法,如下所示:
do{
Statement(s) to be executed;
} 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>
Output 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...