不使用可选链, 使用层级较深的对象下的属性,需要先进行属性值是否存在的判断

    1. const user = {
    2. address: {
    3. street: 'xx街道',
    4. getNum(){
    5. return '80号'
    6. }
    7. }
    8. }
    9. const street = user && user.address && user.address.street
    10. console.log('street', street)
    11. // 判断过于繁琐, 需要先判断是否存在
    12. const num = user && user.address && user.address.getNum && user.address.getNum()
    13. console.log('num', num)

    image.png

    使用可选链 ?.

    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)
    

    image.png
    问号和点是一个整体,不可以分隔