推荐答案
可选链操作符 ?. 允许你访问嵌套对象属性时,如果中间的某个属性为 null 或 undefined,则会短路返回 undefined,而不会抛出错误。这使得处理可能不存在的属性变得更加安全和简洁。
例如:
// www.javascriptcn.com code example
const user = {
profile: {
address: {
city: 'New York'
}
}
};
// 没有可选链,需要显式检查
let city;
if (user && user.profile && user.profile.address) {
city = user.profile.address.city;
}
console.log(city); // "New York"
// 使用可选链
const city2 = user?.profile?.address?.city;
console.log(city2); // "New York"
const user2 = { };
// 没有可选链
let city3;
// console.log(user2.profile.address.city) //报错 Cannot read properties of undefined (reading 'address')
if (user2 && user2.profile && user2.profile.address) {
city3 = user2.profile.address.city;
}
console.log(city3) // undefined
// 使用可选链
const city4 = user2?.profile?.address?.city;
console.log(city4); // undefined本题详细解读
可选链操作符的引入背景
在 JavaScript 中,访问嵌套对象的属性时,经常需要进行多次的 && 操作来避免 TypeError: Cannot read property ... of undefined 类型的错误。这种写法冗长且容易出错。 可选链操作符 ?. 的出现就是为了简化这种写法,提高代码的可读性和健壮性。
可选链操作符的用法
?. 操作符可以用于以下几种场景:
访问对象属性:
obj?.prop- 如果
obj为null或undefined,表达式返回undefined。 - 否则,返回
obj.prop的值。
- 如果
访问数组元素:
arr?.[index]- 如果
arr为null或undefined,表达式返回undefined。 - 否则,返回
arr[index]的值。
- 如果
调用函数:
func?.(args)- 如果
func为null或undefined,表达式返回undefined。 - 否则,调用
func并返回其结果。
- 如果
访问动态属性
obj?.[expression]- 如果
obj为null或undefined,表达式返回undefined。 - 否则,返回
obj[expression]的值。
- 如果
链式使用
?. 最大的优点在于它可以链式使用,即可以在多个层级上进行可选链操作。例如:obj?.prop1?.prop2?.prop3。如果链中的任何一个属性为 null 或 undefined,整个表达式都会返回 undefined,而不会抛出错误。
示例解释
在推荐答案的示例中:
const city2 = user?.profile?.address?.city;这行代码使用了可选链操作符。如果user为null或undefined,则user?.profile会返回undefined,整个表达式也会返回undefined,不会报错。如果user存在,但user.profile为null或undefined,则user?.profile?.address会返回undefined,依此类推。- 这使得我们能够安全地访问深层嵌套的属性,而无需进行大量的
if条件判断。
与 && 的区别
可选链操作符 ?. 和 && 都可以用来避免访问 null 或 undefined 属性时的错误,但是它们的行为略有不同:
&&会进行短路求值,只有在左侧表达式为真值时才会继续执行右侧表达式。如果左侧表达式为假值(例如0,'',false,null,undefined),则直接返回左侧表达式的值。?.只检查左侧表达式是否为null或undefined,如果是则直接返回undefined,否则才会继续访问属性。
因此,?. 更专注于检查 null 和 undefined,而 && 则更关注真值和假值。在访问对象属性时,通常使用 ?. 更加清晰和准确。
注意事项
- 可选链操作符只能用于访问属性,不能用于赋值。
- 可选链操作符返回的始终是
undefined或属性值,不会抛出错误。 ?.操作符只能在 ES2020 及以后的版本中使用。在旧版本的 JavaScript 中,需要使用传统的&&检查或 try-catch 语句来处理null或undefined的情况。