做者:Ashish Lahoti
譯者:前端小智
來源:CSS-Tricket
有夢想,有乾貨,微信搜索 【大遷世界】 關注這個在凌晨還在刷碗的刷碗智。javascript
本文 GitHub https://github.com/qq449245884/xiaozhi 已收錄,有一線大廠面試完整考點、資料以及個人系列文章。前端
可選的連接?.
操做符用於使用隱式空檢查訪問嵌套對象屬性。java
如何使用null (null
和undefined
)檢查訪問對象的嵌套屬性?假設咱們必須從後臺的接口訪問用戶詳細信息。git
能夠使用嵌套的三元運算符 :github
const userName = response ? (response.data ? (response.data.user ? response.data.user.name : null) : null) : null;
或者使用 if
進行空值檢查:面試
let userName = null; if(response && response.data && response.data.user){ userName = response.data.user.name; }
或者更好的方法是使它成爲一個單行連接的&&
條件,像這樣:數組
const userName = response && response.data && response.data.user && response.data.user.name;
上述代碼的共同之處在於,連接有時會很是冗長,而且變得更難格式化和閱讀。這就是 ?.
操做符被提出來的緣由,咱們改下 ?.
重構上面的代碼:微信
const userName = response?.data?.user?.name;
很 nice 呀。工具
?.
語法在ES2020 中被引入,用法以下:this
obj.val?.pro // 若是`val`存在,則返回`obj.val.prop`,不然返回 `undefined`。 obj.func?.(args) // 若是 obj.func 存在,則返回 `obj.func?.(args)`,不然返回 `undefined`。 obj.arr?.[index] // 若是 obj.arr 存在,則返回 `obj.arr?.[index]`,不然返回 `undefined`。
?.
操做符假設咱們有一個 user
對象:
const user = { name: "前端小智", age: 21, homeaddress: { country: "中國" }, hobbies: [{name: "敲代碼"}, {name: "洗碗"}], getFirstName: function(){ return this.name; } }
訪問存在的屬性:
console.log(user.homeaddress.country); // 中國
訪問不存在的屬性:
console.log(user.officeaddress.country); // throws error "Uncaught TypeError: Cannot read property 'country' of undefined"
改用 ?.
訪問不存在的屬性:
console.log(user.officeaddress?.country); // undefined
訪問存在的方法:
console.log(user.getFirstName()); // 前端小智
訪問不存在的方法:
console.log(user.getLastName()); // throws error "Uncaught TypeError: user.getLastName is not a function";
改用 ?.
訪問不存在的方法:
console.log(user.getLastName?.()); // "undefined"
訪問存在的數組:
console.log(user.hobbies[0].name); // "敲代碼"
訪問不存在的方法:
console.log(user.hobbies[3].name); // throws error "Uncaught TypeError: Cannot read property 'name' of undefined"
改用 ?.
訪問不存在的數組:
console.log(user.dislikes?.[0]?.name); // "undefined"
咱們知道 ?.
操做符號若是對象不存在,剛返回 undefined
,開發中可能不返回 undefined
而是返回一個默認值,這時咱們能夠使用雙問題 ??
操做符。
有點抽象,直接來一個例子:
const country = user.officeaddress?.country; console.log(country); // undefined
須要返回默認值:
const country = user.officeaddress?.country ?? "中國"; console.log(country); // 中國
~完,我是刷碗智,SPA走起來,下期見!
代碼部署後可能存在的BUG無法實時知道,過後爲了解決這些BUG,花了大量的時間進行log 調試,這邊順便給你們推薦一個好用的BUG監控工具 Fundebug。