From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- .../operators/conditional_operator/index.html | 101 +++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 files/zh-tw/web/javascript/reference/operators/conditional_operator/index.html (limited to 'files/zh-tw/web/javascript/reference/operators/conditional_operator') diff --git a/files/zh-tw/web/javascript/reference/operators/conditional_operator/index.html b/files/zh-tw/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..78fb9a4a55 --- /dev/null +++ b/files/zh-tw/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,101 @@ +--- +title: 條件運算子 +slug: Web/JavaScript/Reference/Operators/Conditional_Operator +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +
{{jsSidebar("Operators")}}
+ +

條件 (三元) 運算子 是 JavaScript 唯一用到三個運算元的運算子:在一個條件後面會跟著一個問號 (?),如果條件是 truthy,在冒號(:)前的表達式會被執行,如果條件是 falsy,在冒號後面的表達式會被執行,這個運算子常常被用來當作 if 的簡潔寫法.

+ +
{{EmbedInteractiveExample("pages/js/expressions-conditionaloperators.html")}}
+ + + +

語法

+ +
condition ? exprIfTrue : exprIfFalse
+ +

參數

+ +
+
condition
+
值用來做為條件的表達式
+
exprIfTrue
+
如果 condition 的值是 truthy (等於或是可轉換為 true) , exprIfTrue  會被執行
+
exprIfFalse
+
如果 condition 的值是 falsy (等於或是可轉換為 false) , exprIfFalse  會被執行
+
+ +

描述

+ +

除了 false, 可能是 falsy 的表達式有 null, NaN, 0, 空字串 ("") 和 undefined. 如果condition 是他們其中之一 , 那麼條件表達式的結果會是 exprIfFalse 的執行結果. 

+ +

一個簡單的範例:

+ +
var age = 26;
+var beverage = (age >= 21) ? "Beer" : "Juice";
+console.log(beverage); // "Beer"
+
+ +

一個常用來處理 null 的用法 : 

+ +
function greeting(person) {
+    var name = person ? person.name : "stranger";
+    return "Howdy, " + name;
+}
+
+console.log(greeting({name: 'Alice'}));  // "Howdy, Alice"
+console.log(greeting(null));             // "Howdy, stranger"
+
+ +

條件鏈

+ +

條件 (三元) 運算子是右相依性的 (right-associative), 代表他可以以下面的方式鏈結 , 類似於 if … else if … else if … else 的鏈結方法 :

+ +
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; }
+}
+
+ +

規範

+ + + + + + + + + + + + +
Specification
{{SpecName('ESDraft', '#sec-conditional-operator', 'Conditional Operator')}}
+ +

瀏覽器相容性

+ + + +

{{Compat("javascript.operators.conditional")}}

+ +

參見

+ + -- cgit v1.2.3-54-g00ecf