我应该什么时候使用??(无效合并)vs || (逻辑或)?

mik*_*ana 60 javascript logical-or

相关的是有一个“空合并”运营商在JavaScript中?- JavaScript 现在有一个??运算符,我发现它使用得更频繁。以前大多数 JavaScript 代码使用||.

let userAge = null

// These values will be the same. 
let age1 = userAge || 21
let age2 = userAge ?? 21
Run Code Online (Sandbox Code Playgroud)

在什么情况下会??||行为不同?

小智 95

OR操作符||使用正确的值,如果左边是falsy,而nullish合并运算符??使用正确的值,如果左边是nullundefined

如果缺少第一个值,这些运算符通常用于提供默认值。

但是,||如果您的左值可能包含""or0false(因为这些是假值),则 OR 运算符可能会出现问题

console.log(12 || "not found") // 12
console.log(0  || "not found") // "not found"

console.log("jane" || "not found") // "jane"
console.log(""     || "not found") // "not found"

console.log(true  || "not found") // true
console.log(false || "not found") // "not found"

console.log(undefined || "not found") // "not found"
console.log(null      || "not found") // "not found"
Run Code Online (Sandbox Code Playgroud)

在许多情况下,如果 left 是null或,您可能只想要正确的值undefined。这就是空合并运算符??的用途:

console.log(12 ?? "not found") // 12
console.log(0  ?? "not found") // 0

console.log("jane" ?? "not found") // "jane"
console.log(""     ?? "not found") // ""

console.log(true  ?? "not found") // true
console.log(false ?? "not found") // false

console.log(undefined ?? "not found") // "not found"
console.log(null      ?? "not found") // "not found"
Run Code Online (Sandbox Code Playgroud)

虽然该??操作符在当前 LTS 版本的 Node(v10 和 v12)中不可用,但您可以将它用于某些版本的 TypeScript 或 Node:

早在 2019 年 11 月,该??运算符就被添加到TypeScript 3.7中。

最近,该??运算符被包含在 ES2020 中,它由 Node 14(于 2020 年 4 月发布)支持。

??支持空合并运算符时,我通常使用它而不是 OR 运算符||(除非有充分的理由不这样做)。


小智 46

作为一个非常简短的规则,您可以以相反的方式看待它:

  • ||(或者)returns the first "truthy" value(如果不存在“真实”值,则为最后一个值)
  • ??(无效合并)returns the first "defined" value(如果不存在“定义”值,则为最后一个值)

例子

x = false || true; // -->  true   (the first 'truthy' value - parameter 2)
x = false ?? true; // -->  false  (the first 'defined' value - parameter 1)
Run Code Online (Sandbox Code Playgroud)


leo*_*ess 26

简而言之:

所述Nullish合并运算符区分nullishnullundefined)和falsey但定义的值(false0''等等)。有关更多信息,请参阅下图。

对于||(逻辑或)nullish 和falsey 值是相同的。


let x, y

x = 0
y = x || 'default'   // y = 'default'
y = x ?? 'default'   // y = 0
Run Code Online (Sandbox Code Playgroud)

如上所示,运算符??和之间的区别在于||,一个是检查值,一个是检查值。但是,在许多情况下,它们的行为是相同的。那是因为在 JavaScript 中,每个nullish值也是falsey(但并非每个falsey值都是nullish)。

我创建了一个简单的图形来说明JavaScript中nullfalsey值的关系:

在此处输入图片说明

使用我们上面学到的知识,我们可以为不同的行为创建一些示例:

let y

y = false || 'default'       // y = 'default'
y = false ?? 'default'       // y = false

y = 0n || 'default'          // y = 'default'
y = 0n ?? 'default'          // y = 0n

y = NaN || 'default'         // y = 'default'
y = NaN ?? 'default'         // y = NaN

y = '' || 'default'          // y = 'default'
y = '' ?? 'default'          // y = ''
Run Code Online (Sandbox Code Playgroud)

由于新的Nullish Coalescing Operator可以区分无值和假值,例如,如果您需要检查是否有字符串或空字符串,它会很有用。通常,您可能希望使用??而不是||大部分时间。

最后也是最不重要的两个实例,它们的行为相同:

let y

y = null || 'default'        // y = 'default'
y = null ?? 'default'        // y = 'default'

y = undefined || 'default'   // y = 'default'
y = undefined ?? 'default'   // y = 'default'
Run Code Online (Sandbox Code Playgroud)

  • 仅凭图形就可以一目了然地给出令人惊叹的解释 - 很好! (31认同)
  • 喜欢这个解释。在点上! (3认同)

Din*_*nei 17

正如MDN中所述:

与逻辑 OR ( ||) 运算符相反,如果左操作数是不是nullor的假值,则返回左操作数undefined。换句话说,如果您用来||为另一个变量提供一些默认值foo,并且您认为某些虚假值可用(例如''0),则可能会遇到意外行为。请参阅下文了解更多示例。

您链接的问题的答案中:

无论第一个操作数的类型如何,如果将其转换为布尔值结果为 false,则赋值将使用第二个操作数。请注意以下所有情况:

alert(Boolean(null)); // false
alert(Boolean(undefined)); // false
alert(Boolean(0)); // false
alert(Boolean("")); // false
alert(Boolean("false")); // true -- gotcha! :)
Run Code Online (Sandbox Code Playgroud)


Ame*_*icA 14

基于MDN 文档

逻辑 OR (||) 运算符相反,如果左操作数是非or值,则返回左操作数。 nullundefined

概念示例:

真实示例:假设我们有一个phone在表单中不是必需的变量,并且空字符串 ( '') 对我们有效,我们想知道doSomething()phone变量是否为nullundefined,现在猜猜看:

  • 当用于||NOT虚假值时: undefinednull

    const phone = ''; // assume it became empty string from some action
    
    phone || doSomething(); // ==> damn, the doSomething is run 
    // but we want to run it if it's `undefined` or `null` the empty string is valid for us
    
    Run Code Online (Sandbox Code Playgroud)
  • 但是当用于??上述情况时:

    const phone = ''; // same assumption like above
    
    phone ?? doSomething(); // ==> yeah, that's right
    // the empty string is valid for us and the doSomething is not run
    
    Run Code Online (Sandbox Code Playgroud)

注意:实际上这是一个示例,在实际项目中您可以更好地了解这种可爱的操作用法。

注意:他们undefinednull两者的行为相似。


Spe*_*rek 10

||被用作布尔条件时,会变为 false。例如:

let userAge = false

// These values will be the same. 
let age1 = userAge || 21 // 21
let age2 = userAge ?? 21 // false
Run Code Online (Sandbox Code Playgroud)

逻辑 OR 仍将为任何不计算为 的值给出下一个值true。所以它给出了这种情况下的值21。其中??仅处理nullundefined


VLA*_*LAZ 5

function f(input) {
  const val = input || 1;

  return 41 + val;
}

function g(input) {
  const val = input ?? 1;

  return 41 + val;
}

console.log("using ||:", f(0));
console.log("using ??:", g(0));
Run Code Online (Sandbox Code Playgroud)

null(ish) 合并运算符适用于nullundefined。因此,当您不想要这些值时使用 null(ish) 合并运算符,否则您将接受其他虚假值

console.log(null      ?? "nullish");
console.log(undefined ?? "nullish");
console.log(""        ?? "nullish");
console.log(0         ?? "nullish");
console.log(false     ?? "nullish");
Run Code Online (Sandbox Code Playgroud)

逻辑 OR 将跳过任何虚假值并为您提供其他信息。逻辑 OR 将跳过任何虚假值并为您提供另一个参数。 确实 有效并且现在是惯用的,但是它并不总是您想要的:

console.log(null      || "falsy");
console.log(undefined || "falsy");
console.log(""        || "falsy");
console.log(0         || "falsy");
console.log(false     || "falsy");
Run Code Online (Sandbox Code Playgroud)

以下是一些关于如何确定您需要哪一个的规则。最简单的测试:

  • 您是否只想防止null(并且undefined- 通常是同一件事)?然后使用??. 如果您不确定,默认使用空合并运算符可能是个好主意。
  • 例如,您知道您也不想要0""吗?然后使用||.

第二个是它实际上变得棘手的地方。你怎么知道你需要丢弃假值?好吧,第一个片段显示了如果你这样做会发生什么:f(0)将丢弃零,从而产生不同的结果。这是一个有点常见的错误来源。由于该构造a = b || c通常会引入回退值(在本例中c),因此可能会在您无意中意外回退到它。

function updateAge(years) {
  var yearsToAdd = years || 1;
  return this.age + yearsToAdd
}
Run Code Online (Sandbox Code Playgroud)

如果您想为调用提供后备updateAge()(无参数),但如果调用updateAge(0)(无更新)失败,则此方法有效。同样,你可以有:

function sayMyName(greeting) {
  var prefix = greeting || "Hello, my name is ";
  return prefix + this.firstName;
}
Run Code Online (Sandbox Code Playgroud)

同样,这适用于sayMyName()(无参数)但失败sayMyName("")(明确没有问候)。

概括地说,如果您提供与 falsy 值不同的回退值,那么您可能会遇到问题。但是,如果您的回退虚假值 -num || 0否则str || ""它并不重要。

很少(或应该是)您可能期望混合类型(数字、字符串或对象等)并为其提供后备:input || fallback有效但将拒绝空字符串和零。除非您明确不想要其中任何一个,否则通常会出错。

简而言之,您应该始终使用空合并运算符??。确定它是否是一个潜在的错误会减少认知负担。也没有太多理由避免它。它比布尔 OR 新,因此它不适用于较旧的环境,这是真的,但是现在您可能应该为这些环境转译您的代码。如果您不能或不想这样做,那么您别无选择,应该使用布尔 OR。