条件(三元)运算符

条件(三元)运算符是唯一采用三个操作数的 JavaScript 运算符:条件后跟问号 (?),然后是条件为 truthy 时要执行的表达式,后跟冒号 (:),最后是条件是 falsy 时要执行的表达式。此运算符经常用作 if...else 语句的替代。

¥The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as an alternative to an if...else statement.

Try it

语法

¥Syntax

js
condition ? exprIfTrue : exprIfFalse

参数

¥Parameters

condition

一个表达式,其值用作条件。

exprIfTrue

condition 计算结果为 truthy 值(等于或可以转换为 true 的值)时执行的表达式。

exprIfFalse

如果 conditionfalsy(即具有可以转换为 false 的值),则执行的表达式。

描述

¥Description

除了 false 之外,可能的错误表达式还有:nullNaN0、空字符串 ("") 和 undefined。如果 condition 是其中任何一个,则条件表达式的结果将是执行表达式 exprIfFalse 的结果。

¥Besides false, possible falsy expressions are: null, NaN, 0, the empty string (""), and undefined. If condition is any of these, the result of the conditional expression will be the result of executing the expression exprIfFalse.

示例

¥Examples

一个简单的例子

¥A simple example

js
const age = 26;
const beverage = age >= 21 ? "Beer" : "Juice";
console.log(beverage); // "Beer"

处理空值

¥Handling null values

一种常见用法是处理可能是 null 的值:

¥One common usage is to handle a value that may be 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"

条件链

¥Conditional chains

三元运算符是右结合的,这意味着它可以通过以下方式成为 "chained",类似于 if … else if … else if … else 链:

¥The ternary operator is right-associative, which means it can be "chained" in the following way, similar to an if … else if … else if … else chain:

js
function example() {
  return condition1 ? value1
    : condition2 ? value2
    : condition3 ? value3
    : value4;
}

这相当于下面的 if...else 链。

¥This is equivalent to the following if...else chain.

js
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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看