條件運算子
嘗試一下
語法
condition ? exprIfTrue : 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 |
---|
ECMAScript Language Specification # sec-conditional-operator |
瀏覽器相容性
BCD tables only load in the browser