JavaScript 中的循环

JavaScript 有两种不同种类的循环:

for :将一段代码循环执行指定的次数。
while :当指定的条件为 true 时循环执行代码 。
第一:for 循环:在脚本的运行次数已确定的情况下使用 for 循环。
语法:
for (变量=开始值;变量<=结束值;变量=变量+步进值)


{


需执行的代码


}



举例如下:定义了一个循环程序,这个程序中 i 的起始值为 0。每执行一次循环,i 的值就会累加一次 1,循环会一直运行下去,直到 i 等于10 为止。

<html>

<body>

<script type="text/javascript">

var i=0;

for (i=0;i<=10;i++)

{

document.write("The number is " + i);

document.write("<br />");

}

</script>

</body>

</html>

结果如下:

The number is 0

The number is 1

The number is 2

The number is 3

The number is 4

The number is 5

The number is 6

The number is 7

The number is 8

The number is 9

The number is 10

第二:while循环:用于在指定条件为 true 时循环执行代码。语法:

while (变量<=结束值)


{


需执行的代码


}
注意:除了<=,还可以使用其他的比较运算符。
举例如下:定义了一个循环程序,这个循环程序的参数 i 的起始值为 0。该程序会反复运行,直到 i 大于 10 为止。i 的步进值为 1。

<html>

<body>

<script type="text/javascript">

var i=0;

while (i<=10)

{

document.write("The number is " + i);

document.write("<br />");

i=i+1;

}

</script>

</body>

</html>

结果如下:

The number is 0

The number is 1

The number is 2

The number is 3

The number is 4

The number is 5

The number is 6

The number is 7

The number is 8

The number is 9

The number is 10

第三:do...while 循环:

do...while 循环是 while 循环的变种。该循环程序在初次运行时会首先执行一遍其中的代码,然后当指定的条件为 true 时,它会继续这个循环。所以可以这么说,do...while 循环为执行至少一遍其中的代码,即使条件为 false,因为其中的代码执行后才会进行条件验证。
语法:
do


{


需执行的代码


}


while (变量<=结束值)
举例如下:

<html>

<body>

<script type="text/javascript">

var i=0;

do

{

document.write("The number is " + i);

document.write("<br />");

i=i+1;

}

while (i<0)

</script>

</body>

</html>

结果如下:

The number is 0