在Javascript中,只要左边是空的或未定义的,就用nullish coalescing表达式,或者叫??运算符来返回右边的内容。为了更好地理解,让我们看几个例子:
// Is set to 0
let x = 0 ?? "hello";
// Is set to goodbye
let y = undefined ?? "goodbye";
// Is set to hello
let z = null ?? "hello";
// Is set to false
let a = false ?? "goodbye";
nullish coalescing运算符在一些可以返回null或undefined的情况下非常有用,它可以帮助我们收紧代码。例如,可以为某些情况下返回undefined的函数可以提供一个默认值。
let myFunction = (a) => {
if(a >= 5) {
return "hello world";
}
}
// Will return "goodbye world", since `myFunction(4)` returns undefined.
let runFunction = myFunction(4) ?? "goodbye world";
与逻辑OR运算符之间的区别:
过去,我们通常使用逻辑OR(||)运算符在JavaScript中设置缺省值。它具有相同类型的功能,即如果左侧的第一个值不满足特定条件,则设置一个值。但是,如果左边的值是假的,那么||运算符会返回右边的值--并且有很多假的值,如下面的列表所示:
- false
- 0 or -0 or 0n
- any empty string, i.e. ""
- null
- undefined
- NaN
因此,使用||运算符意味着,如果一个函数返回值 0,并且我们确实想要使用 0 值,我们将无法这样做 - 因为 0 是 falsy。对于 nullish coalescing运算符(??),0 是有效值,因为它仅在值为 null 或 undefined 时触发:
// Is set to 0
let x = 0 ?? 5;
// Is set to 5
let y = 0 || 5;
同样,如果字符串为空,则||运算符将默认位于右侧 ,?? 运算符让我们避免这种情况:
// Is set to ""
let x = "" ?? "default text";
// Is set to "default text"
let x = "" || "default text";
还可以链接 nullish coalescing 合并运算符,如下所示:
// Is set to "default text"
let x = null ?? undefined ?? "default text";
但是你不能用逻辑||运算符,除非带括号:
// Errors out:
let x = 0 || undefined ?? "default text";
// Returns "default text";
let y = (0 || undefined) ?? "default text";