JavaScript 循环

for 循环

在脚本的运行次数已确定的情况下使用 for 循环。

语法:

for (变量=开始值;变量<=结束值;变量=变量+步进值) 
{
    需执行的代码
}

实例:

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

注释:步进值可以为负。如果步进值为负,需要调整 for 声明中的比较运算符。

<html>
<body>

<script>
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 循环

while 循环用于在指定条件为 true 时循环执行代码。

语法:

while
(变量<=结束值)
{
    需执行的代码
}

注意:除了<=,还可以使用其他的比较运算符。

实例:

解释:下面的例子定义了一个循环程序,这个循环程序的参数 i 的起始值为 0。该程序会反复运行,直到 i 大于 10 为止。每次运行i的值会增加 1。

<html>
<body>
<script>
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>
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

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值