• 当你必须使用函数表达式(传递匿名函数)时,使用箭头函数标记. eslint: prefer-arrow-callback, arrow-spacing

      原因:它将创建在 this 上下文中执行的函数版本,通常是您想要的,并且语法更简洁

      如果您有一个相当复杂的函数,则可以将该逻辑移到其自己的命名函数表达式中

        // bad
        [1, 2, 3].map(function (x) {
          const y = x + 1
          return x * y
        })
      
        // good
        [1, 2, 3].map((x) => {
          const y = x + 1
          return x * y
        })
    • 如果函数体只包含一条没有副作用的返回表达式的语句,可以省略花括号并使用隐式的 return, 否则保留花括号并使用 return 语句,eslint: arrow-parens, arrow-body-style

      // bad
      [1, 2, 3].map(number => {
        const nextNumber = number + 1
        `A string containing the ${nextNumber}.`
      })
      
      // good
      [1, 2, 3].map(number => `A string containing the ${number}.`)
      
      // good
      [1, 2, 3].map((number) => {
        const nextNumber = number + 1
        return `A string containing the ${nextNumber}.`
      })
      
      // good
      [1, 2, 3].map((number, index) => ({
        index: number
      }))
      
      // No implicit return with side effects
      function foo(callback) {
        const val = callback()
        if (val === true) {
          // Do something if callback returns true
        }
      }
      
      let bool = false
      
      // bad
      foo(() => bool = true)
      
      // good
      foo(() => {
        bool = true
      })
    • 一旦表达式跨多行,使用圆括号包裹以便更好阅读

      // bad
      ['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call(
          httpMagicObjectWithAVeryLongName,
          httpMethod
        )
      )
      
      // good
      ['get', 'post', 'put'].map(httpMethod => (
        Object.prototype.hasOwnProperty.call(
          httpMagicObjectWithAVeryLongName,
          httpMethod
        )
      ))
    • 函数如果只接收一个参数并且没使用用花括号,则省略圆括号,否则为了清晰明确则使用圆括号包裹参数,注意:总是使用圆括号也是可以接受的,eslint 中的 “always” 选项,eslint: arrow-parens

      // bad
      [1, 2, 3].map((x) => x * x)
      
      // good
      [1, 2, 3].map(x => x * x)
      
      // good
      [1, 2, 3].map(number => (
        `A long string with the ${number}. It’s so long that we’ve broken it ` +
        'over multiple lines!'
      ))
      
      // bad
      [1, 2, 3].map(x => {
        const y = x + 1
        return x * y
      })
      
      // good
      [1, 2, 3].map((x) => {
        const y = x + 1
        return x * y
      })
    文档更新时间: 2021-05-13 10:27   作者:姚连洲