這篇文章主要講解了“JavaScript中的可選 (?.)操作符的使用方法”,文中的講解內容簡單清晰,易于學習與理解,下面請大家跟著小編的思路慢慢深入,一起來研究和學習“JavaScript中的可選 (?.)操作符的使用方法”吧!
如何使用null (null
和undefined
)檢查訪問對象的嵌套屬性?假設我們必須從后臺的接口訪問用戶詳細信息。
可以使用嵌套的三元運算符 :
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 中被引入,用法如下:
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); // 中國
感謝各位的閱讀,以上就是“JavaScript中的可選 (?.)操作符的使用方法”的內容了,經過本文的學習后,相信大家對JavaScript中的可選 (?.)操作符的使用方法這一問題有了更深刻的體會,具體使用情況還需要大家實踐驗證。這里是億速云,小編將為大家推送更多相關知識點的文章,歡迎關注!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。