dongxing8009 2017-08-12 05:07
浏览 68
已采纳

我们在JavaScript中有一个更简单的三元运算符吗? [重复]

This question already has an answer here:

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

</div>
  • 写回答

2条回答 默认 最新

  • dongliuxia9495 2017-08-12 05:44
    关注

    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';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?