JavaScript中for循环的使用详解
我们已经看到,while循环有不同变种。本章将介绍另一种流行的循环叫做for循环。
for循环
for循环是循环最紧凑的形式,并包含有以下三个重要部分组成:
- 循环初始化计数器的初始值。初始化语句执行循环开始之前。
- 测试语句,将测试如果给定的条件是真还是假。如果条件为真,那么将要执行的循环中给定的代码,否则循环会退出来。
- 循环语句,可以增加或减少计数器。
可以把所有的三个部分中的一行用分号隔开。
语法
for(initialization;testcondition;iterationstatement){ Statement(s)tobeexecutediftestconditionistrue }
例子:
下面的例子说明一个基本的for循环:
<scripttype="text/javascript"> <!-- varcount; document.write("StartingLoop"+"<br/>"); for(count=0;count<10;count++){ document.write("CurrentCount:"+count); document.write("<br/>"); } document.write("Loopstopped!"); //--> </script>
这将产生以下结果,它类似于while循环:
StartingLoop CurrentCount:0 CurrentCount:1 CurrentCount:2 CurrentCount:3 CurrentCount:4 CurrentCount:5 CurrentCount:6 CurrentCount:7 CurrentCount:8 CurrentCount:9 Loopstopped!