【ES11(2020)】可选链操作符和空值合并运算符
可選鏈操作符 Optional chaining
可選鏈操作符( ?. )允許讀取位于連接對象鏈深處的屬性的值,而不必明確驗證鏈中的每個引用是否有效。?.操作符的功能類似于.鏈式操作符,不同之處在于,在引用為空(nullish) (null或者 undefined) 的情況下不會引起錯誤,該表達式短路返回值是 undefined。與函數調用一起使用時,如果給定的函數不存在,則返回 undefined。
當嘗試訪問可能不存在的對象屬性時,可選鏈操作符將會使表達式更短、更簡明。在探索一個對象的內容時,如果不能確定哪些屬性必定存在,可選鏈操作符也是很有幫助的。
const adventurer = {name: 'Alice',cat: {name: 'Dinah'} };// 直接操作未知的變量和方法有可能報錯 console.log(adventurer.aa.bb) // Uncaught TypeError: Cannot read property 'bb' of undefined console.log(adventurer.aa()) // Uncaught TypeError: adventurer.aa is not a function// 使用可選鏈操作符可避免報錯 const dogName = adventurer.dog?.name; console.log(dogName); // undefinedconsole.log(adventurer.someNonExistentMethod?.()); // undefined語法:
obj?.prop // 對象 obj?.[expr] // 對象 arr?.[index] // 數組 func?.(args) // 函數通過連接的對象的引用或函數可能是 undefined 或 null 時,可選鏈操作符提供了一種方法來簡化被連接對象的值訪問。
比如,思考一個存在嵌套結構的對象 obj。不使用可選鏈的話,查找一個深度嵌套的子屬性時,需要驗證之間的引用,例如:
// 以前的寫法 let nestedProp = obj.first && obj.first.second;// 可選鏈操作符寫法 let nestedProp = obj.first?.second;通過使用 ?.操作符取代.操作符,JavaScript 會在嘗試訪問 obj.first.second 之前,先隱式地檢查并確定 obj.first 既不是 null 也不是 undefined。如果obj.first 是null或者 undefined,表達式將會短路計算直接返回 undefined。
等價于以下表達式,但實際上沒有創建臨時變量:
let temp = obj.first; let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);可選鏈與函數使用
let result = someInterface.customMethod?.();函數使用可選鏈操作符場景:
function doSomething(onContent, onError) {try {// ... do something with the data}catch (err) {onError?.(err.message); // 如果onError是undefined也不會有異常} }可選鏈與表達式
當使用方括號與屬性名的形式來訪問屬性時,你也可以使用可選鏈操作符:
let nestedProp = obj?.['prop' + 'Name'];可選鏈能用于賦值:
let object = {}; object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment可選鏈訪問數組
let arrayItem = arr?.[42];空值合并運算符(Nullish coalescing Operator)
空值合并操作符(??)是一個邏輯操作符,當左側的操作數為 null 或者 undefined時,返回其右側操作數,否則返回左側操作數。
與邏輯或操作符(||)不同,邏輯或操作符會在左側操作數為假值時返回右側操作數。也就是說,如果使用 || 來為某些變量設置默認值,可能會遇到意料之外的行為。比如為假值(例如,’’ 或 0)時。見下面的例子。
const foo = null ?? 'default string'; console.log(foo); // "default string"const baz = 0 ?? 42; console.log(baz); // 0使用空值合并操作符
console.log(null ?? "defaultValue1") // "defaultValue1" console.log(undefined ?? "defaultValue2") // "defaultValue2" console.log("" ?? "defaultValue3") // "" console.log(0 ?? "defaultValue4") // 0 console.log(40 ?? "defaultValue5") // 40為變量賦默認值
以前,如果想為一個變量賦默認值,通常的做法是使用邏輯或操作符(||):
然而,由于||是一個布爾邏輯運算符,左側的操作數會被強制轉換成布爾值用于求值。任何假值(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 = '';let notFalsyText = myText || 'Hello world'; console.log(notFalsyText); // Hello worldlet preservingFalsy = myText ?? 'Hi neighborhood'; console.log(preservingFalsy); // ''短路
與 OR 和 AND 邏輯操作符相似,當左表達式不為 null或 undefined 時,不會對右表達式進行求值。
不能直接與AND或OR操作符共用
null || undefined ?? "foo"; // 拋出 SyntaxError true || undefined ?? "foo"; // 拋出 SyntaxError但是加了括號來表明運算優先級,沒有問題:
(null || undefined ) ?? "foo"; // 返回 "foo"與可選鏈操作符(?.)的關系
let customer = {name: "Carl",details: { age: 82 } }; let customerCity = customer?.city ?? "暗之城"; console.log(customerCity); // “暗之城”總結
以上是生活随笔為你收集整理的【ES11(2020)】可选链操作符和空值合并运算符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: vue.config.js 配置参考
- 下一篇: 【ES6(2015)】Class (类)