一、为什么需要可选链 ?.
在JavaScript中,访问深层嵌套对象属性时,开发者常常面临“中间属性不存在”的崩溃风险。例如:
const user = {};
console.log(user.address.street); // 报错:Cannot read property 'street' of undefined
传统解决方案需要逐层判断(如user.address && user.address.street
),但代码冗长且重复。
二、可选链?.
的语法与作用
可选链操作符?.
允许在访问属性时,若左侧对象为null
或undefined
,则直接返回undefined
而非报错。
console.log(user?.address?.street); // 安全返回undefined
三、?.
操作符的7大核心用法
1. 安全导航对象属性
// 传统写法
const name = user && user.profile && user.profile.name;
// 可选链时代
const name = user?.profile?.name;
2. 防崩溃函数调用
// 安全调用可能不存在的方法
api.getData?.().then(...);
3. 数组元素安全访问
// 传统危险操作
const firstItem = arr[0].property; // 可能报错
// 安全访问
const firstItem = arr?.[0]?.property;
4. 配合空值合并运算符??
const config = user?.settings?.config ?? {};
5. 正则表达式匹配防护
const match = 'string'.match(/pattern/);
const result = match?.[1] ?? 'default';
6. 动态属性访问
const prop = 'firstName';
const value = user?.info?.[prop];
7. 与TypeScript的完美结合
interface User {
profile?: {
email?: string;
}
}
const email = user?.profile?.email; // 自动类型