一、 ?.
可選鏈操作符(?.)允許讀取位于連接對象鏈深處的屬性值,而不必明確驗證鏈中的每個引用是否有效。
let nestedProp = obj.first && obj.first.second;
// 等價于
let nestedProp = obj.first?.second;
js會在嘗試訪問
obj.first.second
之前隱式的檢查并確定obj.first
既不是null
也不是undefined
。如果obj.first
是null
或者undefined
,表達式將會短路計算直接返回undefined
二、??
空值合并操作符,可以在使用可選鏈時設置一個默認值
let customer = {
name: "Carl",
details: { age: 82 }
};
let customerCity = customer?.city ?? "暗之城";
console.log(customerCity); // “暗之城”
三、語法
obj?.prop
obj?.[expr]
arr?.[index]
func?.(args)