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 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型
  • ¥50 buildozer打包kivy app失败
  • ¥30 在vs2022里运行python代码
  • ¥15 不同尺寸货物如何寻找合适的包装箱型谱
  • ¥15 求解 yolo算法问题
  • ¥15 虚拟机打包apk出现错误
  • ¥15 用visual studi code完成html页面