美文网首页
node.js 14新特性

node.js 14新特性

作者: 家有饿犬和聋猫 | 来源:发表于2021-03-02 17:31 被阅读0次

    1 Optional Chaining(可选链)

    const user = {
      name: 'Tom',
      address: {
        city: 'ZhengZhou'
      }
    }
    user.address?.city
    user.address?.city?.length
    
    // 结合 ?.[] 的方式访问相当于 user.address['city']
    user.address?.['city']
    console.log('house', user.address?.house?.z)
    // 结合 delete 语句使用,仅在 user.address.city 存在才删除
    delete user.address?.city
    

    2 Nullish Coalescing(空值合并)
    逻辑或操作符(||)会在左侧为假值时返回右侧的操作符,例如我们传入一个属性为 enabled:0 我们期望输出左侧的值,则是不行的。

    function Component(props) {
      const enable = props.enabled || true; // true
    }
    Component({ enabled: 0 })
    

    现在我们可以使用 空值合并操作符(??)来实现,仅当左侧为 undefined 或 null 时才返回右侧的值。

    function Component(props) {
      const enable = props.enabled ?? true; // 0
    }
    
    Component({ enabled: 0 })
    

    相关文章

      网友评论

          本文标题:node.js 14新特性

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