如果 left 是 falsy,则 OR 运算符使用右值,而 nullish 合并运算符使用 right 值(如果 left 是 或 )。||
??
null
undefined
这些运算符通常用于在缺少第一个运算符时提供默认值。
但是,如果左值可能包含 “”
或 0
或 false
(因为这些是假值),则 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 是 或 ,则可能只需要正确的值。这就是空合并运算符的用途: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"
虽然该运算符在当前 LTS 版本的 Node(v10 和 v12)中不可用,但您可以将其与某些版本的 TypeScript 或 Node 一起使用:??
该运算符于2019年11月添加到TypeScript 3.7中。??
最近,该运算符包含在ES2020中,该操作由Node 14(于2020年4月发布)支持。??
当支持空合并运算符 ??
时,我通常使用它而不是 OR 运算符||
(除非有充分的理由不这样做)。