我什么时候应该使用?? (空位合并)与|| (逻辑或)? [英] When should I use ?? (nullish coalescing) vs || (logical OR)?
问题描述
与相关联;使用JavaScript中的运算符?以前,大多数JavaScript代码都使用||
.
let userAge = null
// These values will be the same.
let age1 = userAge || 21
let age2 = userAge ?? 21
在什么情况下??
和||
的行为会有所不同?
In what circumstances will ??
and ||
behave differently?
推荐答案
The OR operator ||
uses the right value if left is falsy, while the nullish coalescing operator ??
uses the right value if left is null
or undefined
.
如果缺少第一个运算符,通常会使用这些运算符提供默认值.
These operators are often used to provide a default value if the first one is missing.
但是,如果您的左值可能包含""
或0
或false
,则OR运算符||
可能会出现问题(因为它们是
But the OR operator ||
can be problematic if your left value might contain ""
or 0
or false
(because these are falsy values):
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为null
或undefined
时,才可能需要正确的值.这就是无效的合并运算符??
的用途:
In many cases, you might only want the right value if left is null
or undefined
. That's what the nullish coalescing operator ??
is for:
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"
??
运算符在 Node的当前LTS版本中不可用( v10和v12),则可以将其与某些版本的TypeScript或Node一起使用:
While the ??
operator isn't available in current LTS versions of Node (v10 and v12), you can use it with some versions of TypeScript or Node:
The ??
operator was added to TypeScript 3.7 back in November 2019.
最近,??
运算符是ES2020中包含的 ,受Node支持14(于2020年4月发布).
And more recently, the ??
operator was included in ES2020, which is supported by Node 14 (released in April 2020).
当支持无效的合并运算符??
时,我通常使用它代替OR运算符||
(除非有充分的理由不这样做).
When the nullish coalescing operator ??
is supported, I typically use it instead of the OR operator ||
(unless there's a good reason not to).
这篇关于我什么时候应该使用?? (空位合并)与|| (逻辑或)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!