数组

请使用字面量值创建数组

// bad
const items = new Array()

// good
const items = []

向数组中添加元素时,请使用 push 方法

const items = []

// bad
items[items.length] = 'test'

// good
items.push('test')

使用拓展运算符 ... 复制数组

// bad
const items = []
const itemsCopy = []
const len = items.length
let i

for (i = 0; i < len; i++) {
  itemsCopy[i] = items[i]
}

// good
itemsCopy = [...items]

使用数组的 map 等方法时,请使用 return 声明,如果是单一声明语句的情况,可省略 return

// good
[1, 2, 3].map(x => {
  const y = x + 1
  return x - y
})

// good
[1, 2, 3].map(x => x + 1)

// bad
const flat = {}
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
  const flatten = memo.concat(item)
  flat[index] = flatten
})

// good
const flat = {}
[[0, 1], [2, 3], [4, 5]].reduce((memo, item, index) => {
  const flatten = memo.concat(item)
  flat[index] = flatten
  return flatten
})

// bad
inbox.filter((msg) => {
  const { subject, author } = msg
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee'
  } else {
    return false
  }
})

// good
inbox.filter((msg) => {
  const { subject, author } = msg
  if (subject === 'Mockingbird') {
    return author === 'Harper Lee'
  }

  return false
})

results matching ""

    No results matching ""