链式选项(optional chaining)
链式选项 ?.
是在 ES2020 引入的一个新特性。它改变了深层嵌套对象属性值的获取方式。它修复了在获取一长链对象属性的时候不得不进行多次 null 检查的问题。
?.
可以用来检查链式属性的值是否为 null
或者 undefined
。
const prop = obj?.prop1?.prop2?.someProp;
如果任意链式属性的值为 null
或者 undefined
,那么 JS 会返回 undefined
。
let user
console.log(user?.id) // undefined
空合并操作符(nullish coalescing operator)
空合并操作符( ??
)是一个逻辑操作符,如果左侧的操作数(operand)是 null
或者 undefined
,那么它会返回右侧的操作数,反之返回左侧。
与之类似的是逻辑或( ||
)操作符,如果左侧的操作数返回任意的 falsy 值,不仅 null
或 undefined
,它就会返回右侧的操作数。例如,如果左侧的操作数是 ''
或者 0
时,而你又认为它是正确的数,这时候就可以考虑使用 ??
来规避相关问题。
const foo = null ?? 'default string'
console.log(foo) // default string
const bar = 0 ?? 42
console.log(bar) // 0
let customer = {
name: 'Carl',
details: {
age: 82
}
}
const customerCity = customer?.city ?? 'Unknown city'
console.log(customerCity) // Unknown city
操作符优先级
优先级 | 操作类型 | 可结合性 | 单独操作符 |
---|---|---|---|
21 | Grouping | n/a | ( … ) |
20 | member access | 左到右 | xx . xx |
computed member access | 左到右 | … [ … ] |