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!
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短