JS知识点,持续更新

在 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

这里,?. 链式操作符确保了安全的属性访问,而 ?? 提供了默认值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值