「这是我参与11月更文挑战的第22天,活动详情查看:2021最后一次更文挑战」
可选链操作符?.用于访问嵌套对象属性,同时在此过程有隐式空值检查。
1.概述
回想一下,我们是如何访问可能含有空值(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;
2.语法
可选链操作符?.是在 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.
3.用法
以user对象为例,看看?.的用法
const user = {
name: "John",
age: 21,
homeaddress: {
country: "USA"
},
hobbies: [{name: "Coding"}, {name: "Cooking"}],
getFirstName: function(){
return this.name;
}
}
3.1对象
访问存在的属性返回值:
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"
3.2方法
调用存在的方法:
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"
3.3数组
访问数组存在的索引返回值:
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"
3.4与空值合并操作符??一起使用
有的时候,我们希望不返回undefined而是返回一个默认值,这个时候,我们可以使用空值合并操作符??完成这一工作。
不使用??,返回undefined:
const country = user.officeaddress?.country;
console.log(country);
// 打印 "undefined"
与??合用,返回一个默认值
const country = user.officeaddress?.country ?? "China";
console.log(country);
// 打印 "China"
作者:Ashish Lahoti 译者:前端很美 来源:codingnconcepts