百分百源码网-让建站变得如此简单! 登录 注册 签到领金币!

主页 | 如何升级VIP | TAG标签

当前位置: 主页>网站教程>JS教程> JavaScript For While 循环使用方法详解
分享文章到:

JavaScript For While 循环使用方法详解

发布时间:01/15 来源: 浏览: 关键词:
在js中循环包括有 For 循环与while循环,他们区别不大但是在有些地方使用起来会更方法,下面我来给各位同学介绍JavaScript For While 循环使用方法.

for

将一段代码循环执行指定的次数

while

当指定的条件为 true 时循环执行代码

for 循环

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

语法:

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


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

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

 代码如下

<html>
<body>

<script type="text/javascript">
var i=0for (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=0while (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=0do
{
document.write("The number is " + i)
document.write("<br />")
i=i+1
}
while (i<0) </script>
</body>
</html>

结果:
The number is 0

如何退出循环呢,在js中我们可以使用 break 和 continue来退出循环


有两种特殊的语句可用在循环内部:break 和 continue。

Break
break 命令可以终止循环的运行,然后继续执行循环之后的代码(如果循环之后有代码的话)。

实例:

 代码如下

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){break} document.write("The number is " + i)
document.write("<br />")
}
</script>
</body>
</html>

结果:
The number is 0
The number is 1
The number is 2

Continue
continue 命令会终止当前的循环,然后从下一个值继续运行。

实例:

 代码如下

<html>
<body>
<script type="text/javascript">
var i=0
for (i=0;i<=10;i++)
{
if (i==3){continue} 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 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

打赏

打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,你说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

百分百源码网 建议打赏1~10元,土豪随意,感谢您的阅读!

共有5人阅读,期待你的评论!发表评论
昵称: 网址: 验证码: 点击我更换图片
最新评论

本文标签

广告赞助

能出一分力是一分吧!

订阅获得更多模板

本文标签

广告赞助

订阅获得更多模板