在 JavaScript 中,我们经常会使用 || 运算符来对变量进行默认值的设置。例如:
function greet(name) {
name = name || 'world';
console.log(`Hello, ${name}!`);
}
greet(); // Hello, world!
greet('Alice'); // Hello, Alice!在上面的例子中,如果 name 的值为 falsy(比如空字符串、0、false 等),那么 name || 'world' 表达式的结果就是 'world',从而为 name 设置了默认值。
然而,在这种情况下,如果 name 的值为 null 或 undefined,那么默认值 'world' 会被使用,这可能并不是我们想要的行为。
ES11 中引入了一种新的运算符,叫做 nullish 合并运算符 ??,它可以将空值 null 和未定义值 undefined 区分开来。
使用 nullish 合并运算符
nullish 合并运算符的语法很简单,就是 ??,它的作用是如果左侧的值为 null 或 undefined,则使用右侧的值作为默认值。例如:
-- -------------------- ---- ------- -------- ----------- - ---- - ---- -- -------- ------------------- ----------- - -------- -- ------ ------ ------------ -- ------ ------ ----------------- -- ------ ------ --------------- -- ------ ------
在上面的例子中,我们使用了 nullish 合并运算符将 null 和 undefined 区分开来。当 name 的值为 null 或 undefined 时,使用 ?? 运算符将其替换为 'world',从而得到了正确的默认值。
nullish 合并运算符与 || 运算符的区别
使用 nullish 合并运算符可以避免使用 || 运算符时的一些问题。例如,当值为 0 或空字符串 '' 时,|| 运算符会将其视为 falsy,从而使用默认值。而使用 nullish 合并运算符时,只有当值为 null 或 undefined 时才会使用默认值。
-- -------------------- ---- ------- ------------- -- ----------- -- ------- -------------- -- ----------- -- ------- ---------------- -- ----------- -- ------- --------------------- -- ----------- -- ------- ------------- -- ----------- -- - -------------- -- ----------- -- -- ---------------- -- ----------- -- ------- --------------------- -- ----------- -- -------
总结
nullish 合并运算符是 ES11 中的新特性,它可以将空值 null 和未定义值 undefined 区分开来,避免了使用 || 运算符时的一些问题。在编写 JavaScript 代码时,建议使用 nullish 合并运算符来设置默认值,以避免不必要的错误。
示例代码
-- -------------------- ---- ------- -------- ----------- - ---- - ---- -- -------- ------------------- ----------- - ------------- -- ----------- -- ------- -------------- -- ----------- -- ------- ---------------- -- ----------- -- ------- --------------------- -- ----------- -- ------- ------------- -- ----------- -- - -------------- -- ----------- -- -- ---------------- -- ----------- -- ------- --------------------- -- ----------- -- ------- -------- -- ------ ------ ------------ -- ------ ------ ----------------- -- ------ ------ --------------- -- ------ ------
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/65df15d01886fbafa4c5d6bf