【问题标题】:Ternary shorthand for foo ? foo : barfoo 的三元简写?富:酒吧
【发布时间】:2016-02-09 21:56:22
【问题描述】:

我意识到我大部分时间都在使用三元运算符,如下所示:

foo ? foo : bar;

这变得很麻烦,因为可变长度变得很长,例如。 g.

appModel.settings.notifications ? appModel.settings.notifications : {};

是否有任何简写或更优雅的方式来做到这一点? 也许是ES6 或ES7?

【问题讨论】:

  • appModel.settings.notifications || {}
  • 也许appModel.settings.notifications || {}
  • var a = appModel.settings.notifications; a ? a : {};,够短吗?
  • 你对表达式的结果做了什么?
  • 对于foo ? foo : bar 这样简单的情况,您不需要三元。 || 操作员做你想做的事。

标签: javascript ternary-operator shorthand


【解决方案1】:

你可以这样写:

var foo = foo || {};
appModel.settings.notifications = appModel.settings.notifications || {};

你也可以累积

options = default.options || foo.options || bar.options || { foo:'bar'};

【讨论】:

  • 是的,这是JS logical operators 的“好”行为,从左到右评估。但不幸的是,这对于 JS 初学者来说是相当晦涩难懂的……
【解决方案2】:

您可以简单地使用非按位布尔运算符:

foo || bar;

【讨论】:

    【解决方案3】:

    当检查空值时,我们现在可以使用Logical Nullish Assignment:

    foo ??= bar
    

    请参阅 this answer 了解 nullish 和 falsy 之间的区别。

    //these statements are the same for nullish values (null and undefined):
    
    //falsy check
    foo = foo ? foo : bar;
    
    //falsy check
    foo = foo || bar;
    
    //nullish check
    foo ??= bar;
    
    

    【讨论】:

      猜你喜欢
      • 2013-11-01
      • 2011-07-30
      • 1970-01-01
      • 2021-12-19
      • 2014-01-10
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      相关资源
      最近更新 更多