JavaScript 中的循环用来将同一段代码执行指定的次数(或者当指定的条件为 true 时)。
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 循环是 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
Copyright © 2005-2009 www.86w3.com 本站所有文章可自由转载,本站保留网站风格及网页源文件所有版权
本站提供的部分教程文章部分来自互联网或网友发表,纯属学习交流之用,如侵犯您版权的请与我们联系,我们会尽快改正!
粤ICP备07501640号 站长:Knitter web标准技术交流群:37720374