Welcome 微信登录

首页 / 脚本样式 / JavaScript / JavaScript中for循环的使用详解

 我们已经看到,while循环有不同变种。本章将介绍另一种流行的循环叫做for循环。
for 循环
for循环是循环最紧凑的形式,并包含有以下三个重要部分组成:
  1.     循环初始化计数器的初始值。初始化语句执行循环开始之前。
  2.     测试语句,将测试如果给定的条件是真还是假。如果条件为真,那么将要执行的循环中给定的代码,否则循环会退出来。
  3.     循环语句,可以增加或减少计数器。
可以把所有的三个部分中的一行用分号隔开。
语法
for (initialization; test condition; iteration statement){ Statement(s) to be executed if test condition is true}
例子:
下面的例子说明一个基本的for循环:
<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>
这将产生以下结果,它类似于while循环:
Starting LoopCurrent Count : 0Current Count : 1Current Count : 2Current Count : 3Current Count : 4Current Count : 5Current Count : 6Current Count : 7Current Count : 8Current Count : 9Loop stopped!