这次我们来学习JS中的循环语句:while和do~while,这两种语句有什么区别呢?
while循环:进入循环之前检测条件,如不符合,将一次都不执行;
do~while循环:在每次循环结束时在检测条件,无论如何,至少检测一次。
while循环:
语法
while (条件)
{
需要执行的代码
}
案例:
<script>
var i = 0;
while(i<5){
document.write("the number is "+ i + "</br>");
i++;
}
</script>
先定义i的值为0,进入循环体中,当0小于5时,输出当前数字为0,然后i++,也就是i=i+1;现在i变成了1,再次进入循环,1小于5,输出数字为1,i继续加1,直到i的值小于5,停止循环,页面上最终会出现
the number is 0
the number is 1
the number is 2
the number is 3
the number is 4
提示:如果您忘记增加条件中所用变量的值,该循环永远不会结束。该可能导致浏览器崩溃。
do~while循环:
语法
do
{
需要执行的代码
}
while (条件);
案例:
<script>
var i = 0;
do{
document.write("the number is " + i + "</br>");
i++;
}
while(i<4);
</script>
和上面的一样,我们先给i赋值为9,进入循环体,进行第一次循环,输出i的值为0,i++,然后判断条件i是否小于4,是的话继续进行循环,也就是说,无论如何都会先进行一次循环,然后再判断条件。页面效果如下:
the number is 0
the number is 1
the number is 2
the number is 3