switch 語句又名《分支語句》,很多資料把他稱之爲if語句的兄弟語句。
在if語句中條件過多的時候可以使用switch 語句來簡化代碼。
先看一下語法:
switch (expression){
case value: statement;
break;
case value: statement;
break;
case value: statement;
break;
default: statement;
}
解釋一下:
1、expression是傳過來的值
2、value是需要滿足的條件
3、statement是滿足之後執行的函數
4、default是默認值(一般都不滿足的時候會執行)
5、break跳出switch語句
下面咱們也不要太囉嗦了來個例子說明一下:
var a = 6;
switch (a){
case 0 : {
console.log(0)(www.gendna5.com)
}
break;
case 1: console.log(1);
break;
case 2: console.log(2);
break;
case ((a>=3 && a<=5) ? a : 1): console.log(345);
break;
case 6: console.log(6);
break;
default: console.log('沒有');
}
上面的代碼,咱們可以改一下a的值來實驗一下。
文章開頭說過switch語句是爲了簡化if語句的,上面的代碼咱們寫個對應功能的if語句
if(a == 0){
console.log(0)
}else if(a == 1){
console.log(1);
}else if(a == 2){
console.log(2);
}else if ( 3 <= a && a<=5 ){
console.log(345);
}else if (a == 6){
console.log(6);
}else{
console.log('沒有');
}
當然,if和switch到底用那個?,這個主要看團隊是怎麼定義的和程序本身的環境來決定