我应该什么时候使用 ??(零合并)与||(逻辑 OR)?总之:

2022-08-30 01:29:04

JavaScript中是否有“空合并”运算符有关? - JavaScript现在有一个我看到更频繁使用的运算符。以前大多数JavaScript代码都使用。??||

let userAge = null

// These values will be the same. 
let age1 = userAge || 21
let age2 = userAge ?? 21

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


答案 1

如果 left 是 falsy,则 OR 运算符使用右值,而 nullish 合并运算符使用 right 值(如果 left 是 或 )。||??nullundefined

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

但是,如果左值可能包含 “”0false(因为这些是假值),则 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"

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

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"

虽然该运算符在当前 LTS 版本的 Node(v10 和 v12)中不可用,但您可以将其与某些版本的 TypeScript 或 Node 一起使用:??

该运算符于2019年11月添加到TypeScript 3.7中。??

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

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


答案 2

总之:

Nullish 合并运算符区分 nullishnull未定义)和 falsey 但定义的值(false0'' 等)。有关详细信息,请参阅下图。

对于||(逻辑 OR)空值和 falsey 值是相同的。


let x, y

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

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

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

enter image description here

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

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 = ''

由于新的 Nullish 合并运算符可以区分无值和 falsey 值,因此,如果您需要检查是否没有字符串或空字符串,则可能会有所帮助。通常,您可能希望使用而不是大多数时间。??||

最后,也是至少这里是它们行为相同的两个实例:

let y

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

y = undefined || 'default'   // y = 'default'
y = undefined ?? 'default'   // y = 'default'