您好,欢迎访问一九零五行业门户网

JavaScript中循环知识的介绍(代码示例)

本篇文章给大家带来的内容是关于javascript中循环知识的介绍(代码示例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
for 循环
在脚本的运行次数已确定的情况下使用 for 循环。
语法:
for (变量=开始值;变量<=结束值;变量=变量+步进值) { 需执行的代码}
实例:解释:下面的例子定义了一个循环程序,这个程序中 i 的起始值为 0。每执行一次循环,i 的值就会累加一次 1,循环会一直运行下去,直到 i 等于 10 为止。
注释:步进值可以为负。如果步进值为负,需要调整 for 声明中的比较运算符。
<html><body><script>var i=0for (i=0;i<=10;i++){document.write("the number is " + i)document.write("<br />")}</script></body></html>
结果:the number is 0the number is 1the number is 2the number is 3the number is 4the number is 5the number is 6the number is 7the number is 8the number is 9the number is 10

while 循环while 循环用于在指定条件为 true 时循环执行代码。
语法:while(变量<=结束值){ 需执行的代码}
注意:除了<=,还可以使用其他的比较运算符。
实例:解释:下面的例子定义了一个循环程序,这个循环程序的参数 i 的起始值为 0。该程序会反复运行,直到 i 大于 10 为止。每次运行i的值会增加 1。
<html><body><script>var i=0while (i<=10){document.write("the number is " + i)document.write("<br />")i=i+1}</script></body></html>
结果:the number is 0the number is 1the number is 2the number is 3the number is 4the number is 5the number is 6the number is 7the number is 8the number is 9the number is 10

do...while 循环do...while 循环是 while 循环的变种。该循环程序在初次运行时会首先执行一遍其中的代码,然后当指定的条件为 true 时,它会继续这个循环。所以可以这么说,do...while 循环为执行至少一遍其中的代码,即使条件为 false,因为其中的代码执行后才会进行条件验证。
语法:do{ 需执行的代码}while(变量<=结束值)
实例:<html><body><script>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
以上就是javascript中循环知识的介绍(代码示例)的详细内容。
其它类似信息

推荐信息