• 当需要使用对象的多个属性时,请使用解构赋值,eslint: prefer-destructuring

      愿意:解构可以避免创建属性的临时引用

      // bad
      function getFullName (user) {
        const firstName = user.firstName
        const lastName = user.lastName
      
        return `${firstName} ${lastName}`
      }
      
      // good
      function getFullName (user) {
        const { firstName, lastName } = user
      
        return `${firstName} ${lastName}`
      }
      
      // better
      function getFullName ({ firstName, lastName }) {
        return `${firstName} ${lastName}`
      }
    • 当需要使用数组的多个值时,请同样使用解构赋值,eslint: prefer-destructuring

      const arr = [1, 2, 3, 4]
      
      // bad
      const first = arr[0]
      const second = arr[1]
      
      // good
      const [first, second] = arr
    • 函数需要回传多个值时,请使用对象的解构,而不是数组的解构

      原因:可以非破坏性地随时增加或者改变属性顺序

      // bad
      function doSomething () {
        return [top, right, bottom, left]
      }
      
      // 如果是数组解构,那么在调用时就需要考虑数据的顺序
      const [top, xx, xxx, left] = doSomething()
      
      // good
      function doSomething () {
        return { top, right, bottom, left }
      }
      
      // 此时不需要考虑数据的顺序
      const { top, left } = doSomething()
    文档更新时间: 2021-05-11 16:00   作者:姚连洲