【问题标题】:When to use logical nullish operator over logical OR operator? [duplicate]何时使用逻辑空运算符而不是逻辑 OR 运算符? [复制]
【发布时间】:2022-01-01 06:15:24
【问题描述】:

根据definition nullish assignment ,仅当变量为 null 或未定义时才分配。但是,也可以使用 OR 运算符完成相同的操作,如下例所示。我们应该在哪里使用空赋值运算符而不是逻辑 OR 运算符?

let a = null;
let b = undefined;
a ||= 10;
console.log(a); // output: 50

b ||= 'string is empty.';
console.log(b); // output: "string is empty."

let a = null;
let b = undefined;

a ??= 10;
console.log(a);  // output: 50

b ??= 'string is empty.';
console.log(b); // output: "string is empty."

【问题讨论】:

    标签: javascript


    【解决方案1】:

    ?? 在您不想检查所有 falsy 值时很有用:

    const bla = 0;
    const foo = bla ?? 1; // 0 is a falsy value but ?? only checks null/undefined
    console.log(foo)

    const bla = 0;
    const foo = bla || 1; // `bla` can be any falsy value and `foo` will be 1
    console.log(foo)

    【讨论】:

      猜你喜欢
      • 2023-03-12
      • 1970-01-01
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多