JavaScript 空值合并操作符 ??

477 阅读2分钟

空值合并操作符??) 是一个逻辑操作符。
当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

逻辑或操作符||)不同,由于 || 是一个布尔逻辑运算符,左侧的操作数会被强制转换成布尔值用于求值,逻辑或操作符会在左侧操作数为false时返回右侧操作数。也就是说,如果使用 || 来为某些变量设置默认值,可能会遇到意料之外的行为。比如为假值(例如,0''NaN)时。见下面的例子。

const result = null ?? 'default value';
console.log(result); // default value

const num = 0 ?? 42;
console.log(num); // 0

语法

leftExpr ?? rightExpr

赋默认值

为变量赋默认值,通常的做法是使用逻辑或操作符(||):

let notAssignedValue;
//  notAssignedValue 为 undefined
const result = notAssignedValue || 'Hello!';

然而,由于 || 是一个布尔逻辑运算符,任何假值(0''NaNnullundefined)都不会被返回。这导致如果你使用0''NaN作为有效值,就会出现不可预料的后果。

let count = 0;
let text = "";

let num = count || 42;
let message = text || "hi!";
console.log(num);     // 42,而不是 0
console.log(message); // "hi!",而不是 ""

空值合并操作符可以避免这种陷阱,其只在第一个操作数为nullundefined 时(而不是其它假值)返回第二个操作数:

let myText = '';

let rightSideResult = myText || 'Hello world';
console.log(rightSideResult); // Hello world

let leftSideResult = myText ?? 'Hi neighborhood';
console.log(leftSideResult); // ''

短路效应

OR (||)AND(&&) 逻辑操作符相似,当左表达式为 nullundefined 时,会对右表达式进行求值。

function A() { console.log('函数 A 被调用了'); return undefined; }
function B() { console.log('函数 B 被调用了'); return false; }
function C() { console.log('函数 C 被调用了'); return "result"; }

console.log( A() ?? C() );
// 依次打印 "函数 A 被调用了"、"函数 C 被调用了"、"result"
// A() 返回了 undefined,所以操作符两边的表达式都被执行了

console.log( B() ?? C() );
// 依次打印 "函数 B 被调用了"、"false"
// B() 返回了 false(既不是 null 也不是 undefined)
// 所以右侧表达式没有被执行

不能与 && 或 || 操作符共用

?? 直接与 AND(&&)和 OR(||)操作符组合使用是不可取的。(注:应当是因为空值合并操作符和其他逻辑操作符之间的运算优先级/运算顺序是未定义的)这种情况下会抛出 SyntaxError

null || undefined ?? "result"; // 抛出 SyntaxError
true || undefined ?? "result"; // 抛出 SyntaxError

但是,如果使用括号来显式表明运算优先级,是没有问题的:

(null || undefined ) ?? "result"; // 返回 "result"

与可选链式操作符(?.)的关系

空值合并操作符针对 undefinednull 这两个值,可选链操作符?.) 也是如此。在这访问属性可能为 undefinednull 的对象时,可选链操作符非常有用。

let myInfo = { name: "hero" };

console.log(myInfo.name?.toUpperCase()); // "HERO"
console.log(myInfo.school?.toUpperCase()); // undefined

具体有关可选链式操作符(?.) 可阅读这篇文章JavaScript 可选链操作符 ?.