此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。
条件(三元)运算符
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2015年7月.
条件(三元)运算符是 JavaScript 唯一使用三个操作数的运算符:一个条件后跟一个问号(?),如果条件为真值,则执行冒号(:)前的表达式;若条件为假值,则执行最后的表达式。该运算符经常当作if...else 语句的简捷形式来使用。
In this article
尝试一下
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参数
condition计算结果用作条件的表达式。
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 值
一个常见的用法是处理可能为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; }}规范
| Specification |
|---|
| ECMAScript® 2026 Language Specification> # sec-conditional-operator> |