多个if...else连接在一起使用的时候,可以转为使用更方便的switch结构
表达式→值1→语块1→break;→
表达式→值2→语块1→break;→
表达式→defalut→默认语块→
switch(fruit){
case"banana":
//...
break;
case"apple":
//...
default:
//...
}
需要注意的是,每个case代码块内部的break语句不能少,否则会接下去执行下一个case代码块,而不是跳出switch结构。
var x = 1;
switch(x){
case 1:
console.log("x=1");
case 2:
console.log("x=2");
default:
console.log("x=其他值");
}
//x等于1
//x等于2
//x等于其他值