条件运算符

条件运算符

条件(三元)运算符是 JavaScript 仅有的使用三个操作数的运算符。一个条件后面会跟一个问号(?),如果条件为 truthy ,则问号后面的表达式A将会执行;表达式A后面跟着一个冒号(:),如果条件为 if 语句的简捷形式来使用。

The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

语法

condition ? exprIfTrue : exprIfFalse

参数

condition

计算结果用作条件的表达式

exprIfTrue

如果表达式

condition 的计算结果是

truthy(它和

true 相等或者可以转换成

true ),那么表达式

exprIfTrue 将会被求值。

exprIfFalse

如果表达式

condition 的计算结果是

falsy(它可以转换成

false ),那么表达式

exprIfFalse 将会被执行。

描述

除了 false,可能的假值表达式还有: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"

Note: The optional chaining operator 设计用来处理这种使用场景。在本文档写成的时候 (2019.01),这个运算符还处于实验阶段并且没有实现。

条件链

这个三元操作符是右结合的,也就是说你可以像这样把它链接起来, 和 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

Status

Comment

ECMAScript Latest Draft (ECMA-262)Conditional Operator

Draft

ECMAScript 2015 (6th Edition, ECMA-262)Conditional Operator

Standard

ECMAScript 5.1 (ECMA-262)The conditional operator

Standard

ECMAScript 1st Edition (ECMA-262)The conditional operator

Standard

Initial definition. Implemented in JavaScript 1.0.

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out

https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop

Mobile

Server

Chrome

Edge

Firefox

Internet Explorer

Opera

Safari

Android webview

Chrome for Android

Firefox for Android

Opera for Android

Safari on iOS

Samsung Internet

Node.js

Conditional operator (c ? t : f)

Chrome Full support 1

Edge Full support 12

Firefox Full support 1

IE Full support 3

Opera Full support Yes

Safari Full support Yes

WebView Android Full support 1

Chrome Android Full support 18

Firefox Android Full support 4

Opera Android Full support Yes

Safari iOS Full support Yes

Samsung Internet Android Full support 1.0

nodejs Full support Yes

Legend

Full support

Full support

相关资讯