From 33058f2b292b3a581333bdfb21b8f671898c5060 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:40:17 -0500 Subject: initial commit --- .../operators/conditional_operator/index.html | 115 +++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 files/ja/web/javascript/reference/operators/conditional_operator/index.html (limited to 'files/ja/web/javascript/reference/operators/conditional_operator') diff --git a/files/ja/web/javascript/reference/operators/conditional_operator/index.html b/files/ja/web/javascript/reference/operators/conditional_operator/index.html new file mode 100644 index 0000000000..19afa5445a --- /dev/null +++ b/files/ja/web/javascript/reference/operators/conditional_operator/index.html @@ -0,0 +1,115 @@ +--- +title: 条件 (三項) 演算子 +slug: Web/JavaScript/Reference/Operators/Conditional_Operator +tags: + - Conditional + - JS + - JavaScript + - Operator + - Reference + - ternary + - 三項 + - 条件 + - 演算子 +translation_of: Web/JavaScript/Reference/Operators/Conditional_Operator +--- +
{{jsSidebar("Operators")}}
+ +

条件 (三項) 演算子は JavaScript では唯一の、3 つのオペランドをとる演算子です。条件に続いて疑問符 (?)、そして条件が{{Glossary("truthy", "真値")}}であった場合に実行する式、コロン (:) が続き、条件が{{Glossary("falsy")}}であった場合に実行する式が最後に来ます。この演算子は、 if 文のショートカットとしてよく用いられます。

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

構文

+ +
condition ? exprIfTrue : exprIfFalse
+ +

引数

+ +
+
condition
+
値が条件として使用される式です。
+
exprIfTrue
+
condition が {{Glossary("truthy")}} の値 (true と等しいか、 true に変換できる値) と評価された場合に評価される式です。
+
exprIfFalse
+
condition が {{Glossary("falsy")}} の値 (false と等しいか、 false に変換できる値) と評価された場合に評価される式です。
+
+ +

解説

+ +

false についていえば、 falsy になる可能性がある式は null, NaN, 0, 空文字列 (""), undefined です。 condition がこのうちの何れかであれば、条件演算子の結果は exprIfFalse の式を実行した結果になります。

+ +

+ +

単純な例

+ +
var age = 26;
+var beverage = (age >= 21) ? "ビール" : "ジュース";
+console.log(beverage); // "ビール"
+
+ +

null 値の扱い

+ +

よくある使い方の一つに、 null になる可能性がある値を扱うというものがあります。

+ +
let greeting = person => {
+    let name = person ? person.name : `お客さん`
+    return `やあ、${name}`
+}
+
+console.log(greeting({name: `アリス`}));  // "やあ、アリス"
+console.log(greeting(null));             // "やあ、お客さん"
+
+ +

条件の連鎖

+ +

三項演算子は右結合で、すなわち以下のような方法で if … else if … else if … else の連鎖と同様に「連鎖」させることができます。

+ +
function example(…) {
+    return condition1 ? value1
+         : condition2 ? value2
+         : condition3 ? value3
+         : value4;
+}
+
+// 以下のものと同等です。
+
+function example(…) {
+    if (condition1) { return value1; }
+    else if (condition2) { return value2; }
+    else if (condition3) { return value3; }
+    else { return value4; }
+}
+
+ +

仕様書

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

ブラウザーの互換性

+ + + +

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

+ +

関連情報

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