一、為什么需要可選鏈 ?.
在JavaScript中,訪問深層嵌套對象屬性時,開發(fā)者常常面臨“中間屬性不存在”的崩潰風險。例如:
const user = {};
console.log(user.address.street); // 報錯:Cannot read property 'street' of undefined
傳統(tǒng)解決方案需要逐層判斷(如user.address && user.address.street),但代碼冗長且重復。
二、可選鏈?.的語法與作用
可選鏈操作符?.允許在訪問屬性時,若左側(cè)對象為null或undefined,則直接返回undefined而非報錯。
console.log(user?.address?.street); // 安全返回undefined
三、?.操作符的7大核心用法
1. 安全導航對象屬性
// 傳統(tǒng)寫法
const name = user && user.profile && user.profile.name;
// 可選鏈時代
const name = user?.profile?.name;
2. 防崩潰函數(shù)調(diào)用
// 安全調(diào)用可能不存在的方法
api.getData?.().then(...);
3. 數(shù)組元素安全訪問
// 傳統(tǒng)危險操作
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. 動態(tài)屬性訪問
const prop = 'firstName';
const value = user?.info?.[prop];
7. 與TypeScript的完美結(jié)合
interface User {
profile?: {
email?: string;
}
}
const email = user?.profile?.email; // 自動類型