溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

JavaScript中的可選 (?.)操作符的使用方法

發(fā)布時(shí)間:2021-06-15 13:42:43 來源:億速云 閱讀:211 作者:chen 欄目:web開發(fā)

這篇文章主要講解了“JavaScript中的可選 (?.)操作符的使用方法”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“JavaScript中的可選 (?.)操作符的使用方法”吧!

如何使用null (nullundefined)檢查訪問對(duì)象的嵌套屬性?假設(shè)我們必須從后臺(tái)的接口訪問用戶詳細(xì)信息。

可以使用嵌套的三元運(yùn)算符 :

const userName = response ? (response.data ? (response.data.user ? response.data.user.name : null) : null) : null;

或者使用 if 進(jìn)行空值檢查:

let userName = null;
if(response && response.data && response.data.user){
  userName = response.data.user.name;
}

或者更好的方法是使它成為一個(gè)單行鏈接的&&條件,像這樣:

const userName = response && response.data && response.data.user && response.data.user.name;

上述代碼的共同之處在于,鏈接有時(shí)會(huì)非常冗長(zhǎng),并且變得更難格式化和閱讀。這就是 ?.操作符被提出來的原因,我們改下 ?. 重構(gòu)上面的代碼:

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`。

使用?.操作符

假設(shè)我們有一個(gè) user 對(duì)象:

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"

數(shù)組

訪問存在的數(shù)組:

console.log(user.hobbies[0].name); 
// "敲代碼"

訪問不存在的方法:

console.log(user.hobbies[3].name); 
// throws error "Uncaught TypeError: Cannot read property 'name' of undefined"

改用 ?. 訪問不存在的數(shù)組:

console.log(user.dislikes?.[0]?.name); 
// "undefined"

?? 操作符

我們知道 ?. 操作符號(hào)如果對(duì)象不存在,剛返回 undefined,開發(fā)中可能不返回 undefined 而是返回一個(gè)默認(rèn)值,這時(shí)我們可以使用雙問題 ?? 操作符。

有點(diǎn)抽象,直接來一個(gè)例子:

const country = user.officeaddress?.country;
console.log(country);
// undefined

需要返回默認(rèn)值:

const country = user.officeaddress?.country ?? "中國";
console.log(country);
// 中國

感謝各位的閱讀,以上就是“JavaScript中的可選 (?.)操作符的使用方法”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)JavaScript中的可選 (?.)操作符的使用方法這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI