条件(三元)运算符
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
条件(三元)运算符是 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"
语法
condition ? exprIfTrue : exprIfFalse
参数
condition
-
计算结果用作条件的表达式。
exprIfTrue
-
如果
condition
的计算结果为真值(等于或可以转换为true
的值),则执行该表达式。 exprIfFalse
-
如果
condition
为假值(等于或可以转换为false
的值)时执行的表达式。
描述
除了 false
,可能的假值表达式还有:null
、NaN
、0
、空字符串(""
)和 undefined
。如果 condition
是其中任何一个,那么条件表达式的结果就是 exprIfFalse
表达式执行的结果。
示例
简单的例子
const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"
处理 null 值
一个常见的用法是处理可能为 null
的值:
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
链:
function example() {
return condition1
? value1
: condition2
? value2
: condition3
? value3
: value4;
}
这等价于以下 if...else
链。
function example() {
if (condition1) {
return value1;
} else if (condition2) {
return value2;
} else if (condition3) {
return value3;
} else {
return value4;
}
}
规范
Specification |
---|
ECMAScript® 2025 Language Specification # sec-conditional-operator |
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | server | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Conditional operator ( c ? t : f ) |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support