Do we have a simpler ternary operator in JavaScript? [duplicate]

一世执手 提交于 2020-05-02 00:13:54

问题


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';

Why don't we have the same in JavaScript?

I am tired of doing:

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

回答1:


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.

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

As the documentation explains:

Logical OR (||)

expr1 || expr2

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.

Instead of writing

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

you can use the shorter:

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';



回答2:


In javascript you can do the following:

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

If the first value is false (null, false, 0, NaN, "" or undefined), then the second value is going to be assigned.



来源:https://stackoverflow.com/questions/45646722/do-we-have-a-simpler-ternary-operator-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!