??(空值合并操作符)
当左侧值为 nullundefined 时,返回 ?? 符号右边的值

案例如下:

'hello world' ?? 'hi' 
// 'hello world'

'' ?? 'hi' 
// ''

false ?? 'hi' 
// false

null ?? 'hi'  
// 'hi'

undefined ?? 'hi'
// 'hi'


?.(可选链操作符)
允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。

案例如下:

let network = {
	chain: 1,
	name: 'ethereum'
}
let res = network?.name
// 返回 ethereum

let customer = {
  name: "Carl",
  details: {
    age: 82,
    location: "Paradise Falls" // details 的 address 属性未有定义
  }
};
let customerCity = customer.details?.address?.city;
// 由于 details 中 address 属性未有定义, 因此返回 undefined


参考资料:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐