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