作者:Ashish Lahoti
译者:前端小智
起源:CSS-Tricket

有幻想,有干货,微信搜寻 【大迁世界】 关注这个在凌晨还在刷碗的刷碗智。

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试残缺考点、材料以及我的系列文章。

可选的链接?.操作符用于应用隐式空查看拜访嵌套对象属性。

概述

如何应用null (nullundefined)查看拜访对象的嵌套属性?假如咱们必须从后盾的接口拜访用户详细信息。

能够应用嵌套的三元运算符 :

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);// 中国

~完,我是刷碗智,SPA走起来,下期见!


代码部署后可能存在的BUG没法实时晓得,预先为了解决这些BUG,花了大量的工夫进行log 调试,这边顺便给大家举荐一个好用的BUG监控工具 Fundebug。

原文:https://codingncoepts.com/jav...