' for '循环是最紧凑的循环形式。它包括以下三个重要部分 :
循环初始化我们初始化我们的计数器到一个起始值。初始化语句在循环开始之前执行。
测试语句将测试给定条件是否为真。如果条件为真,那么循环内给出的代码将被执行,否则控件将退出循环。
迭代声明你可以增加或减少你的计数器。
你可以将所有三个部分放在一行中分开分号。
JavaScript中 for 循环的流程图如下 :
for 循环的语法是JavaScript如下 :
for(initialization; test condition; iteration statement) { 如果测试条件为真,则执行的声明 }
尝试以下示例,了解 for 循环如何在JavaScript中运行。
<html> <body> <script type = "text/javascript"> <!-- var count; document.write("Starting Loop" + "<br />"); for(count = 0; count < 10; count++) { document.write("Current Count : " + count ); document.write("<br />"); } 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...