在 JavaScript 中, ?. 被称为可选链操作符(Optional Chaining Operator)。它是一种用于安全访问对象深层嵌套属性的语法,能够避免在访问不存在的属性时抛出错误。
1. 基本用法 当你想要访问一个对象的嵌套属性时,如果某个中间属性可能是 null 或 undefined ,使用可选链操作符可以防止代码抛出错误。
const user = {
name: "张三",
address: {
street: "123路",
city: "上海"
}
};
console.log(user.address?.street); // 输出: "123路"
console.log(user.address?.zipcode); // 输出: undefined
console.log(user.contact?.phone); // 输出: undefined
2. 避免错误 使用可选链操作符的好处是,它可以避免在访问深层嵌套属性时出现的 TypeError 。如果使用传统的点操作符( . ),当某个中间属性是 null 或 undefined 时,代码会抛出错误。
// 使用传统的点操作符
console.log(user.address.street); // 正常输出
console.log(user.contact.phone); // 抛出 TypeError: Cannot read property 'phone' of undefined
// 使用可选链操作符
console.log(user.contact?.phone); // 输出: undefined,安全访问
3. 与其他操作符结合使用 可选链操作符可以与其他操作符结合使用,比如数组索引、函数调用等。
const users = [
{ name: "Alice", age: 30 },
{ name: "Bob", age: 25 },
null,
{ name: "Charlie", age: 35 }
];
console.log(users[2]?.name); // 输出: undefined console.log(users[1]?.name); // 输出: "Bob"
在这个例子中,访问 users[2]?.name 返回 undefined ,因为 users[2] 是 null ,而不会抛出错误。