可选的链接?。运算符用于通过隐式空检查访问嵌套对象属性。概述如何使用null(null和undefined)检查访问对象的嵌套属性?假设我们必须从后端的接口访问用户详细信息。您可以使用嵌套的三元运算符:constuserName=response?(response.data?(response.data.user?response.data.user.name:null):null:null;或使用if进行空值检查:letuserName=null;if(response&&response.data&&response.data.user){userName=response.data.user.name;}或更好地使其成为这样的单行链接&&条件:constuserName=响应&&response.data&&response.data.user&&response.data.user.name;上面代码的共同点是链接有时会非常冗长并且变得难以格式化和阅读。这就是为什么?.运营商被提议。让我们改变?。重构上面的代码:constuserName=response?.data?.user?.name;很不错。语法?。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`。使用?。operator假设我们有一个用户对象:constuser={name:"前端小智",age:21,homeaddress:{country:"China"},hobbies:[{name:"敲代码"},{name:"洗碗"}],getFirstName:function(){returnthis.name;}}Propertyaccesstoexistingproperties:console.log(user.homeaddress.country);//中国访问不存在的属性:console.log(user.officeaddress.country);//throwserror"UncaughtTypeError:Cannotreadproperty'country'ofundefined"改用?.访问不存在的属性:console.log(user.officeaddress?.country);//undefined方法访问已有方法:console.log(user.getFirstName());//前端小智访问不存在的方法:console.log(user.getLastName());//throwserror"UncaughtTypeError:user.getLastNameisnotfunction";使用?。access不存在的方法:console.log(user.getLastName?.());//“undefined”数组访问存在的数组:console.log(user.hobbies[0].name);//“敲代码”访问不存在的方法:console.log(user.hobbies[3].name);//throwserror"UncaughtTypeError:Cannotreadproperty'name'ofundefined"使用?反而。访问不存在的数组:console.log(user.dislikes?.[0]?.name);//"undefined"??我们知道的运营商?运算符号如果该对象不存在,只是返回未定义。在开发过程中,它可能不会返回undefined而是一个默认值。这时候,我们可以用双问??运算符有点抽象,直接举个例子:constcountry=user.officeaddress?.country;console.log(country);//undefined需要返回默认值:constcountry=user.officeaddress?.country??"China";console.log(country);//China~完了,我干得漂亮,我去SPA了,下期见!作者:AshishLahoti译者:FrontendXiaozhi来源:CSS-Tricket》,可通过以下二维码关注,转载请联系大千世界公众号。
