巩固一下 JS 可选 (?.)操做符号,原来函数也能够用可选写法,又学到了!

做者:Ashish Lahoti
译者:前端小智
来源:CSS-Tricket

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

本文 GitHub https://github.com/qq449245884/xiaozhi 已收录,有一线大厂面试完整考点、资料以及个人系列文章。前端

可选的连接?.操做符用于使用隐式空检查访问嵌套对象属性。java

概述

如何使用null (nullundefined)检查访问对象的嵌套属性?假设咱们必须从后台的接口访问用户详细信息。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

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

相关文章
相关标签/搜索