【问题标题】:Any difference between x || [] and x ?? [] in javascript?x || 之间的任何差异[] 和 x ?? [] 在 JavaScript 中?
【发布时间】:2021-10-28 21:00:55
【问题描述】:

我已经看到 x || []x ?? [] 都用于在 x 为空时提供备用值。有没有这两种给出不同结果的情况?

【问题讨论】:

标签: javascript nullish-coalescing


【解决方案1】:

如果x 是一个非空的假值,那就不同了。

x = 0;
x = x ?? []
console.log(x);



y = null;
y = y ?? []
console.log(y);

【讨论】:

    【解决方案2】:

    他们做不同的事情。

    ?? 被称为 Nullish 合并运算符 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator

    并检查评估的左侧是否为空或未定义,如果不是,则分配评估的右侧。

    当您检查具有值zero 的变量时,前一个非常有用,如果您正在检查它,这将是错误的。

    || 是逻辑运算符https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR

    logical operator 与任何其他逻辑运算符一样工作。将评估左侧,然后评估右侧

    null || 1 // output 1
    undefined || 1 // output 1
    0 || 1 // 1 <-- there are cases where you want to treat zero as a truthy value and **that's where the nullish operator is handy**
    

    【讨论】:

    • 0 || 1 返回 1,所以也许您的意思是 desired 结果为 0,但 cmets 并不清楚。 ;-)
    • 是的,这就是我想说的......将更新评论:祈祷:
    【解决方案3】:

    x || []x ?? [] 这些表达式是 Javascript 中的逻辑赋值。

    x ?? [] 用于表示 nullundefined 情况,而x || [] 表示true 如果abtrue

    • x ?? [] 通过评估表达式的左侧是否为空或未定义来工作。

    • x || [] 的工作原理是评估 ab 是否为 true。如果a 为真,则在 if 语句中继续。如果b 为真,则继续执行 if 语句。

    【讨论】:

      猜你喜欢
      • 2017-03-02
      • 1970-01-01
      • 2021-10-07
      • 1970-01-01
      • 2021-01-24
      • 2021-11-28
      • 2021-07-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多