当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JavaScript中for循环的使用详解

JavaScript中for循环的使用详解

2019年08月03日  | 移动技术网IT编程  | 我要评论

 我们已经看到,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 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! 

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网