JS中鮮為人知的知識點-空值合并運算符(??)
與邏輯或操作符(||)不同,邏輯或操作符會在左側操作數為假值時返回右側操作數。也就是說,如果使用 || 來為某些變量設置默認值,可能會遇到意料之外的行為。比如為假值(例如,'' 或 0)時。見下面的例子。
const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"
const baz = 0 ?? 42;
console.log(baz);
// expected output: 0
示例
使用空值合并操作符
在這個例子中,我們使用空值合并操作符為常量提供默認值,保證常量不為 null 或者 undefined。
const nullValue = null;
const emptyText = ""; // 空字符串,是一個假值,Boolean("") === false
const someNumber = 42;
const valA = nullValue ?? "valA 的默認值";
const valB = emptyText ?? "valB 的默認值";
const valC = someNumber ?? 0;
console.log(valA); // "valA 的默認值"
console.log(valB); // ""(空字符串雖然是假值,但不是 null 或者 undefined)
console.log(valC); // 42
為變量賦默認值
以前,如果想為一個變量賦默認值,通常的做法是使用邏輯或操作符(||):
let foo;
// foo is never assigned any value so it is still undefined
let someDummyText = foo || 'Hello!';
然而,由于 || 是一個布爾邏輯運算符,左側的操作數會被強制轉換成布爾值用于求值。任何假值(0, '', NaN, null, undefined)都不會被返回。這導致如果你使用0,''或NaN作為有效值,就會出現不可預料的后果。
let count = 0;
let text = "";
let qty = count || 42;
let message = text || "hi!";
console.log(qty); // 42,而不是 0
console.log(message); // "hi!",而不是 ""
空值合并操作符可以避免這種陷阱,其只在第一個操作數為null 或 undefined 時(而不是其它假值)返回第二個操作數:
let myText = ''; // An empty string (which is also a falsy value)
let notFalsyText = myText || 'Hello world';
console.log(notFalsyText); // Hello world
let preservingFalsy = myText ?? 'Hi neighborhood';
console.log(preservingFalsy); // '' (as myText is neither undefined nor null)
短路
與 OR 和 AND 邏輯操作符相似,當左表達式不為 null 或 undefined 時,不會對右表達式進行求值。
function A() { console.log('函數 A 被調用了'); return undefined; }
function B() { console.log('函數 B 被調用了'); return false; }
function C() { console.log('函數 C 被調用了'); return "foo"; }
console.log( A() ?? C() );
// 依次打印 "函數 A 被調用了"、"函數 C 被調用了"、"foo"
// A() 返回了 undefined,所以操作符兩邊的表達式都被執行了
console.log( B() ?? C() );
// 依次打印 "函數 B 被調用了"、"false"
// B() 返回了 false(既不是 null 也不是 undefined)
// 所以右側表達式沒有被執行
不能與 AND 或 OR 操作符共用
將 ?? 直接與 AND(&&)和 OR(||)操作符組合使用是不可取的。(譯者注:應當是因為空值合并操作符和其他邏輯操作符之間的運算優先級/運算順序是未定義的)這種情況下會拋出 SyntaxError 。
null || undefined ?? "foo"; // 拋出 SyntaxError
true || undefined ?? "foo"; // 拋出 SyntaxError
但是,如果使用括號來顯式表明運算優先級,是沒有問題的:
(null || undefined ) ?? "foo"; // 返回 "foo"
與可選鏈式操作符(?.)的關系
空值合并操作符針對 undefined 與 null 這兩個值,可選鏈式操作符(?.) 也是如此。在這訪問屬性可能為 undefined 與 null 的對象時,可選鏈式操作符非常有用。
let foo = { someFooProp: "hi" };
console.log(foo.someFooProp?.toUpperCase()); // "HI"
console.log(foo.someBarProp?.toUpperCase()); // undefined