面试题答案
一键面试可选链操作符(?.)的作用
可选链操作符(?.)用于在访问对象的深层属性、调用函数或访问数组元素时,当对象为 null
或 undefined
时,不会抛出错误,而是直接返回 undefined
。它提供了一种更简洁和安全的方式来处理可能不存在的对象引用。
安全地访问对象的深层属性
假设我们有一个嵌套的对象结构,比如:
const user = {
address: {
city: 'New York'
}
};
如果我们想要访问 user.address.city
,在没有可选链操作符时,需要进行繁琐的检查:
let city;
if (user && user.address) {
city = user.address.city;
} else {
city = undefined;
}
使用可选链操作符,可以简化为:
const city = user?.address?.city;
如果 user
为 null
或 undefined
,或者 user.address
为 null
或 undefined
,city
都会被赋值为 undefined
,而不会抛出错误。
在函数调用中的应用
假设我们有一个对象,它可能有一个方法,比如:
const obj = {
// sayHello: () => console.log('Hello')
};
没有可选链操作符时,调用方法前需要检查方法是否存在:
if (obj.sayHello) {
obj.sayHello();
}
使用可选链操作符:
obj?.sayHello?.();
如果 obj
为 null
或 undefined
,或者 obj.sayHello
为 null
或 undefined
,不会抛出错误,而是直接跳过函数调用。
在数组访问中的应用
假设我们有一个可能为 null
或 undefined
的数组,想要访问其中的元素,比如:
let arr: number[] | undefined;
// arr = [1, 2, 3];
没有可选链操作符时,需要检查数组是否存在:
let firstElement;
if (arr) {
firstElement = arr[0];
} else {
firstElement = undefined;
}
使用可选链操作符:
const firstElement = arr?.[0];
如果 arr
为 null
或 undefined
,firstElement
会被赋值为 undefined
,而不会抛出错误。