## if與switch的使用時機 ### 概述 * `if`適用於條件為**某一範圍**的情況,`switch`適用於**條件明確**的情況 * 由於`switch`使用**嚴格比較**,並不會自動轉換型別,需注意`expression`與`case value`的撰寫 1. `if...else` statement ```javascript const score = 75; if (score === 100) { console.log ("滿分") } else if (score >= 60 && score < 100) { console.log ("及格") } else if (score >= 0 && score < 60) { console.log ("不及格") } else { console.log ("分數有誤") } ``` 2. `switch` statement ```javascript const score = 75; // expression, value皆為true才執行特定case switch (true) { case (score === 100): console.log ("滿分"); break; case (score >= 60 && score < 100): console.log ("及格"); break; case (score >= 0 && score < 60): console.log ("不及格"); break; default: console.log ("分數有誤") } ``` ### 關於`switch` statement * syntax: ```javascript switch (expression) { case value1: statements break; case value2: statements break; // … case valueN: statements break; default: statements break; } ``` * 使用要點: 1. expression與case進行比對時,使用嚴格邏輯運算子`===` 2. 若沒有`break`,將會從符合條件的`case`開始執行**每一個**`case`,直到陳述式結束 ```javascript const value = 1; switch (value) { case 0: console.log (0) case 1: console.log (1) case 2: console.log (2) } // output 1 2 ``` 3. 可同時使用多個`case`進行判斷 ```javascript function monthDays (month) { switch (month) { case 2: return 28 case 4: case 6: case 9: case 11: return 30 default: return 31 } } ``` 4. `default`為optional,當沒有任何`case`符合條件時會執行 * 參考文章: * [[JavaScript] 條件判斷:if…else 與 switch](https://hackmd.io/@lunzaizai/BJk9KR18t) * [switch - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch#lexical_scoping) ## 三元運算子 ### 概述 * syntax: `condition ? <expression if true> : <expression if false>` * 作為`if`的簡潔寫法 * 除了false,也能處理其他**假值**:`null`、`NaN`、`0`、空字串`""`以及`undefined` * ==💡注意:空物件`{}`、空陣列`[]`為truthy== * 實務上可利用三元運算子來處理`null`: ```javascript function greeting (name) { name = name ? name : "stranger" console.log (`Hello, ${name}.`) } greeting (); // Hello, stranger. greeting ("Jon") // Hello, Jon. ``` ### 條件鏈 * 語法具備右依性 (right-associative),可以鏈結成類似`if...else if...else`的結構 * syntax: ```javascript function example(…) { return condition1 ? value1 : condition2 ? value2 : condition3 ? value3 : value4; } // Equivalent to: function example(…) { if (condition1) { return value1; } else if (condition2) { return value2; } else if (condition3) { return value3; } else { return value4; } } ``` * 參考文章: * [Conditional (ternary) operator - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator) ## 邏輯運算的短路性質 (短路求值) Short-circuit evaluation ### 概述 * 在特定的邏輯運算情境中,從第一個運算元 (operand) 即可得出結果,不需要進一步判斷第二個運算元,因此可利用此短路特性撰寫更簡潔的判斷式,例如: 1. 當`&&`的第一個運算元為falsy時,其結果必定為false,回傳第一個值 2. 當`||`的第一個運算元為truthy時,其結果必定為true,回傳第一個值 * 無法利用短路特性來判斷的情況,繼續檢視第二個運算元 1. 當`&&`的運算元皆為truthy時,回傳**最後一個**值 2. 當`||`的運算元皆為falsy時,回傳**最後一個**值 * 除了boolean,也可回傳**其他型別**的值 ### 短路求值的應用 * 利用`&&`檢查物件屬性是否存在 ```javascript let customer = { userId: "ID2314", cartItem: ["book", "mug"], // coupon: ["10% off", "25% off", "50% off"] } // 確認購物車商品及優惠券 customer.cartItem && console.log (`您的購物車有${customer.cartItem.length}樣商品`) customer.coupon && console.log (`共${customer.coupon.length}張優惠券待使用`) ``` * 利用`||`設定預設值 ```javascript function greeting (name) { name = name || "stranger" console.log (`Hello, ${name}.`) } greeting ("Jon"); // Hello, Jon. greeting (""); // Hello, stranger. ``` ### 補充資料 * 邏輯運算子的**執行優先序** 1. `&&`運算子的執行優先序高於`||`,存在多個運算子時會依優先序進行判斷,撰寫時須留意 ```javascript true || false && false; // true (true || false) && false; // false ``` 2. 其他運算子優先序見MDN表格:[operator precedence - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence#table) * 真假值表:[A standard IF statement](https://dorey.github.io/JavaScript-Equality-Table/) * 參考文章: * [Logical AND (&&) - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND) * [Logical OR (||) - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR) * [JavaScript基本功修練:Day9 - 短路求值與條件運算子的應用](https://ithelp.ithome.com.tw/articles/10243261)