流程控制语句、循环语句

if

if语句是编程语言最常用的语句,语法

if(condition){
    //true statement
}else {
    //false statement
}

switch

switch(expresstion){
    case value1:
        statement;
        break;
    case value2:
        statement;
        break;
    case value3:
        statement;
        break;
    default:
        statement;
}

break跳出switch语句,不添加会多次判断case,没有符合的case会进入default。常见用法

switch(a){
    case 1:
        statement;
        break;
    case 2:
        statement;
        break;
    case 3:
        statement;
        break;
    default:
        statement;
}

while

var i = 10;
while(i > 0){
    console.log(i);
    i--;
}

do-while

var i = 4;
do{
    console.log(i);
    i--;
}while(i > 5);

for

for(var i = 10; i > 0; i--){
    console.log(i);
}

for-in

for-in是一种迭代语句,用于枚举对象的属性

for(var prop in window){
    console.log(prop);
}

break和continue

break 用于强制退出循环体,执行循环后面的语句
continue 用于退出本次循环,执行下次循环

for(var i = 1; i< 10; i++){
    if(i % 4 === 0){
        break;
    }
    console.log(i);
}
//1 2 3
for(var i = 1; i< 10; i++){
    if(i % 4 === 0){
        continue;
    }
    console.log(i);
}
//1 2 3 5 6 7 8 9

你可能感兴趣的:(流程控制语句、循环语句)