在 JavaScript 中,?. 和 ?? 是两个不同的操作符,用于处理可选链和空值合并。
1.可选链操作符 ?.
可选链操作符(Optional Chaining Operator)允许读取对象的属性或调用对象的方法,而不需要明确判断对象及其嵌套属性是否存在。
举例:
const person = {
name: 'John',
address: {
city: 'New York',
},
};
// 不使用可选链,需要显式判断
const city = person && person.address && person.address.city;
// 使用可选链
const cityWithOptionalChaining = person?.address?.city;
console.log(city); // 输出: New York
console.log(cityWithOptionalChaining); // 输出: New York
在上面的例子中,?. 允许我们在不明确检查每个属性的情况下安全地访问 person 对象的属性。
2.空值合并操作符 ??
空值合并操作符(Nullish Coalescing Operator)用于提供默认值,当左侧的操作数为 null 或 undefined 时,使用右侧的操作数。
举例:
const defaultValue = 'Default Value';
const userValue = null;
// 使用空值合并操作符
const result = userValue ?? defaultValue;
console.log(result); // 输出: Default Value
在上面的例子中,?? 用于检查 userValue 是否为 null 或 undefined,如果是,则使用 defaultValue 作为结果。
综合使用示例:
const person = {
name: 'John',
address: {
city: 'New York',
},
};
const cityName = person?.address?.city ?? 'Default City';
console.log(cityName); // 输出: New York
const missingCityName = person?.address?.nonExistentCity ?? 'Default City';
console.log(missingCityName); // 输出: Default City
这里,?. 链式操作符确保了安全的属性访问,而 ?? 提供了默认值。