JavaScript之循环语句

(1)while语句

while(条件){
条件为真,进入循环体。出现0 null undefined false其中任意一种情况,条件即为假
循环体
}

案例:

var n=0;
var count=0;
while (n<100) {
// 条件为真时,进入循环体。为了避免出现死循环,条件不能永远为真
n++;
count+=n;
// count=count+n;
}
console.log(count);

(2)do-while语句

do{
循环体
}while(条件)
do-while:先执行一次循环体,再判断条件,条件为假时,跳出循环
while:先判断条件,如果条件为真,则执行循环体,否则跳出循环

案例:

var b=0;
do{
console.log('B');
b++;
}while(b==2)

(3)for循环语句

for(循环初始条件;循环约束条件;循坏继续下去的条件){
循环体
}

执行步骤:
1、执行循环初始条件,只执行一次
2、执行循环约束条件,如果条件满足,执行循环体,否则跳出循环
3、执行循环体
4、执行循坏继续下去的条件

案例:九九乘法表

for(var i=1;i<10;i++){
for(var j=1;j<=i;j++){
if(i*j<10){
document.write(j+'*'+i+'='+i*j+'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;');
}else{
document.write(j+'*'+i+'='+i*j+'&nbsp;&nbsp;&nbsp;');
}
}
document.write('<br>');
}

猜你喜欢

转载自www.cnblogs.com/msw0803/p/11526963.html