JavaScript的循环


for循环是循环的最紧凑形式,它包括以下三个重要部分:

  • 循环初始化在这里我们将计数器初始化为起始值。初始化语句在循环开始之前执行;

  • 测试声明它将测试给定条件是否为真。如果条件为真,则将执行循环内给出的代码,否则控件将退出循环;

  • 迭代语句你可以在其中增加或减少计数器。

你可以将所有三个部分放在由分号分隔的一行中。

语法


JavaScript中for循环的语法如下:

for (initialization; test condition; iteration statement) {
    Statement(s) to be executed if test condition is true
}

请尝试以下示例,以了解如何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...