请使用字面量值创建数组,eslint: no-array-constructor
// 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 // bad for (i = 0; i < len; i++) { itemsCopy[i] = items[i] } // good itemsCopy = [...items]
把一个可迭代的对象转换为数组时,使用展开运算符
...
而不是Array.from
const foo = document.querySelectorAll('.foo') // good const nodes = Array.from(foo) // best const nodes = [...foo]
使用
Array.from
来将一个类数组对象转换为数组const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 } // bad const arr = Array.prototype.slice.call(arrLike) // good const arr = Array.from(arrLike)
遍历迭代器进行映射时使用
Array.from
代替扩展运算符...
, 因为这可以避免创建中间数组// bad const baz = [...foo].map(bar) // good const baz = Array.from(foo, bar)
使用数组的
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 })
如果一个数组有多行则要在数组的开括号后和闭括号前使用新行
// bad const arr = [ [0, 1], [2, 3], [4, 5] ] const objectInArray = [{ id: 1 }, { id: 2 }] const numberInArray = [ 1, 2 ] // good const arr = [[0, 1], [2, 3], [4, 5]] const objectInArray = [ { id: 1 }, { id: 2 } ] const numberInArray = [ 1, 2 ]
文档更新时间: 2021-05-11 16:00 作者:姚连洲