可选链操作符(Optional Chaining Operator)是 ECMAScript 2020(ES11)引入的一项功能,用于更安全地访问对象的属性或方法。这个操作符的主要目的是处理在访问嵌套对象的属性或方法时,可能会遇到 null 或 undefined 值的情况,以防止抛出错误。
可选链操作符的语法形式是 ?.,可以用来代替传统的访问操作符 .。它可以应用于对象属性、数组元素和函数方法的调用,下面是一些示例:
访问对象属性:
const person = {
name: 'Alice',
address: {
city: 'New York',
},
};
const cityName = person.address?.city;
console.log(cityName); // 输出 'New York'
const age = person.age?.toString();
console.log(age); // 输出 undefined,因为 person 对象中没有 age 属性
访问数组元素:
const numbers = [1, 2, 3, 4, 5];
const thirdNumber = numbers[2]?.toFixed(2);
console.log(thirdNumber); // 输出 '3.00'
const nonExistentElement = numbers[10]?.toFixed(2);
console.log(nonExistentElement); // 输出 undefined,因为数组索引 10 不存在
调用函数方法:
const person = {
name: 'Bob',
sayHello() {
return `Hello, ${this.name}!`;
},
};
const greeting = person.sayHello?.();
console.log(greeting); // 输出 'Hello, Bob!'
const missingMethod = person.sayGoodbye?.();
console.log(missingMethod); // 输出 undefined,因为 sayGoodbye 方法不存在
可选链操作符允许你避免在访问不存在的属性或方法时抛出 TypeError 错误,而是安全地返回 undefined。这在处理复杂的对象结构、从外部数据源获取数据或执行可选的操作时非常有用,可以简化代码并提高代码的健壮性。