其他分享
首页 > 其他分享> > ES2020新特性链操作符 '?.'和'??'

ES2020新特性链操作符 '?.'和'??'

作者:互联网

ES2020新特性,js中的可选链操作符?.

概述

回想一下,我们是如何访问可能含有空值(null或undefined)属性的嵌套对象,比如访问web api 返回结果的user详情,可以使用嵌套的三元运算符像这样:

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;

语法

可选链操作符 ?. 是在 Javascript ES2020 中引入的,其语法如下:

obj.val?.prop       如果val存在返回 obj.val.prop, 否则 undefined.
obj.func?.(args)    如果func存在返回 obj.func(args) , 否则 undefined.
obj.arr?.[index]    如果array存在返回 obj.array[index] , 否则 undefined.

用法

以user对象为例,学习 ?. 的用法

const user = {
  name: "John",
  age: 21,
  homeaddress: {
    country: "USA"
  },
  hobbies: [{name: "Coding"}, {name: "Cooking"}],
  getFirstName: function(){
    return this.name;
  }
}
对象

访问存在的属性返回值:

console.log(user.homeaddress.country); 
// 打印 "USA";

访问不存在的属性会报错:

console.log(user.officeaddress.country); 
// throws error "Uncaught TypeError: Cannot read property 'country' of undefined"

使用可选链操作符 ?. 访问不存在的属性。返回 undefined

console.log(user.officeaddress?.country); 
// 打印 "undefined"
方法

调用存在的方法:

console.log(user.getFirstName()); 
// 打印 "John";

调用不存在的方法会抛出异常

console.log(user.getLastName()); 
// throws error "Uncaught TypeError: user.getLastName is not a function";

使用可选链操作符 ?. 访问不存在的方法,返回 undefined

console.log(user.getLastName?.()); 
// prints "undefined"
数组

访问数组存在的索引返回值:

console.log(user.hobbies[0].name); 
// 打印 "Coding";

访问数组不存在的索引抛出异常:

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

使用可选链操作符 ?. 访问数组不存在的索引,返回 undefined

console.log(user.hobbies[3]?.name); 
// prints "undefined"

访问不存在的数组,会抛出异常

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

使用可选链操作符 ?. 访问不存在的数组,返回 undefined :

console.log(user.dislikes?.[0]?.name); 
// prints "undefined"
与空值合并操作符??一起使用

有的时候,我们希望不返回 undefined 而是返回一个默认值,这个时候,我们可以使用空值合并操作符??完成这一工作。

不使用 ?? ,返回 undefined :

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

?? 合用,返回一个默认值

const country = user.officeaddress?.country ?? "China";
console.log(country);
// 打印 "China"

标签:log,console,name,ES2020,特性,操作符,user,response,undefined
来源: https://www.cnblogs.com/MutualExchange/p/15631285.html