條件(三元)運算子
條件(三元)運算子是 JavaScript 中唯一一個接受三個運算元的運算子:一個條件,後跟一個問號 (?),然後是當條件為真值時執行的表示式,後跟一個冒號 (:),最後是當條件為假值時執行的表示式。此運算子常用於替代if...else語句。
試一試
function getFee(isMember) {
return isMember ? "$2.00" : "$10.00";
}
console.log(getFee(true));
// Expected output: "$2.00"
console.log(getFee(false));
// Expected output: "$10.00"
console.log(getFee(null));
// Expected output: "$10.00"
語法
js
condition ? exprIfTrue : exprIfFalse
引數
條件-
一個值用作條件的表示式。
exprIfTrue-
如果
condition的求值結果為真值(即等於或可以轉換為true的值),則執行的表示式。 exprIfFalse-
如果
condition為假值(即其值可以轉換為false),則執行的表示式。
描述
除了 false,可能的假值表示式有:null、NaN、0、空字串 ("") 和 undefined。如果 condition 是這些值中的任何一個,則條件表示式的結果將是執行表示式 exprIfFalse 的結果。
示例
一個基本示例
js
const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"
處理空值
一個常見的用法是處理可能為 null 的值
js
const greeting = (person) => {
const name = person ? person.name : "stranger";
return `Howdy, ${name}`;
};
console.log(greeting({ name: "Alice" })); // "Howdy, Alice"
console.log(greeting(null)); // "Howdy, stranger"
條件鏈
三元運算子是右結合的,這意味著它可以按以下方式“鏈式”使用,類似於 if … else if … else if … else 鏈
js
function example() {
return condition1 ? value1
: condition2 ? value2
: condition3 ? value3
: value4;
}
這等同於以下if...else鏈。
js
function example() {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}
規範
| 規範 |
|---|
| ECMAScript® 2026 語言規範 # sec-conditional-operator |
瀏覽器相容性
載入中…