我们在JavaScript中是否有一个更简单的三元运算符? [英] Do we have a simpler ternary operator in JavaScript?

查看:60
本文介绍了我们在JavaScript中是否有一个更简单的三元运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在PHP中看到了这种语法:

I just saw this syntax in PHP:

// Fetches the value of $_GET['user'] and returns 'nobody'
// if it does not exist.
$username = $_GET['user'] ?? 'nobody';

为什么我们在JavaScript中没有相同的内容?

Why don't we have the same in JavaScript?

我厌倦了这样做:

var name = obj['name'] ? obj['name'] : 'GOD';

推荐答案

提出十多年后,在PHP 7(于2015年12月发布)中引入的. .

The Null coalescing operator is a recent addition to PHP. It was introduced in PHP 7 (released in December 2015), more than 10 years after the feature was proposed for the first time.

在Javascript中,逻辑OR 运算符可以用于此目的达很长时间(自Java自是创建的?!).

In Javascript, the logical OR operator can be used for this purpose for ages (since Javascript was created?!).

作为文档解释:

逻辑或(||)

Logical OR (||)

expr1 || expr2

返回expr1,如果可以将其转换为true;否则,返回expr2.
因此,当与布尔值一起使用时,如果任一操作数为true,则||返回true;否则,返回true.如果两者均为false,则返回false.

Returns expr1 if it can be converted to true; otherwise, returns expr2.
Thus, when used with Boolean values, || returns true if either operand is true; if both are false, returns false.

代替写作

var name = obj['name'] ? obj['name'] : 'GOD';

您可以使用简称:

var name = obj['name'] || 'GOD';

||运算符可以多次使用,以创建一个较长的表达式,该表达式的值等于第一个不为空的操作数的值:

The || operator can be used several times to create a longer expression that evaluates to the value of the first operand that is not empty:

var name = obj['name'] || obj['desc'] || 'GOD';

这篇关于我们在JavaScript中是否有一个更简单的三元运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆