不使用可选链, 使用层级较深的对象下的属性,需要先进行属性值是否存在的判断
const user = {
address: {
street: 'xx街道',
getNum(){
return '80号'
}
}
}
const street = user && user.address && user.address.street
console.log('street', street)
// 判断过于繁琐, 需要先判断是否存在
const num = user && user.address && user.address.getNum && user.address.getNum()
console.log('num', num)
使用可选链 ?.
const user = {
address: {
street: 'xx街道',
getNum(){
return '80号'
}
}
}
const street = user?.address?.street
const num = user?.address?.getNum?.()
console.log('street', street)
console.log('num', num)
问号和点是一个整体,不可以分隔