美文网首页组件
开发中常用的es6(时常更新)

开发中常用的es6(时常更新)

作者: 逸笛 | 来源:发表于2021-10-18 09:59 被阅读0次

    最近开发中,发现一些比较好用的es6

    1.可选链操作符 '?.'
    场景:获取对象属性值。
    项目中一个很常见的场景,从接口返回的数据,对象中的某个属性可能不存在,即 undefined ;或者尝试获取 DOM 元素,该元素不存在,即 null 。
    eg:cat 属性可能不存在:

    const  home={
    name:'Amy',
    cat:{
    name:'King'}
    }
    

    如果想要访问 cat 的 name 属性,像下面这样可能会报错:

    const  name=home.cat.name
    

    Uncaught TypeError: Cannot read property ‘name’ of undefined

    没用es6之前,使用and运算符:

    const  name=home&&home.cat&&home.cat.name
    

    使用es6的可选链操作符 '?.'

    const  name=home?.cat?.name
    

    相关文章

      网友评论

        本文标题:开发中常用的es6(时常更新)

        本文链接:https://www.haomeiwen.com/subject/mlngoltx.html