??(空值合并操作符)
当左侧值为 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

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐