DAY 12
0
Modern Web

# 菜菜菜的前端學習日誌 - Day12

### 判斷式

#### if

``````if(a > b){
console.log('Hello');
}                     //當a > b時就會出現Hello
``````

if後的()內的判斷式是會判斷是否為true，如果為true才會執行{}內的程式碼。

``````var a = true;
var b = false;
if(a){
console.log('Hello');
}                      //a為true，所以會出現Hello

if(!b){
console.log('Hello');
}                         //也為true，所以會出現Hello

``````

``````a && console.log('Hello');

b || console.log('Hello');
``````

#### if else

``````var a = 3;
var b = 5;
if(a > b){
console.log('Hello');
}else{
console.log('bye');
}                        //因為a沒有大於b為false，所以會出現bye

a > b ? console.log('Hello') : console.log('bye')
``````

#### else if

``````var a = 5;
var b = 5;
if(a > b){
console.log('Hello');
}else if(a < b){
console.log('bye');
}else{
console.log('good job')
}                        //因為a不大於b也不小於b，所以直接到else執行程式
``````

#### switch

switch是先列出一個判斷的標的，接下來與case做判斷是否為true，若為true就會執行該程式碼

``````var a = "42";
switch(a){
case 2:
break;
case 42:
break;
default:
break;
}
``````

``````var a = "42";
switch(true){
case a == 2:
break;
case a == 42:
break;
default:
break;
}
``````

``````var a = "42";
switch(true){
case a === 2:
break;
case a === 42:
break;
default:
break;
}
``````

===是嚴格相等，他必須值相等型別也香等他才會為true。

``````var a = 42;
switch(a){
case 1:
case 2:
default:
case 3:
break;
case 4:
}
``````