js数组迭代方法妙用

180 阅读1分钟

1. 使用 fill 方法批量造数据

const testData = Array(200).fill({
    id: 'xx',
    name: 'xxx'
})

这样就可以快速的造出多行数据,但这样造出的数据每行都一样,而且是同个引用, 造出每行不一样的数据可以这样:

const testData = Array(200).fill().map((v, i) => ({
    id: i + 1,
    name_number: parseInt(Math.random() * 100000)
}))

2. reduce 的妙用

reduce 的使用示例大多都是使用求和,其实还可以很多秒用,

  1. 为了方便取值,将数组转化对象
const arr = [
    { value: '1', label: 'xx1' },
    { value: '2', label: 'xx2' },
    { value: '3', label: 'xx3' },
    { value: '4', label: 'xx4' }
]
const obj = arr.reduce((t, v) => {
    t[v.value] = v.label
    return t
}, {})
  1. 获取数组中某些条件下的指定字段,如数组中 status 为 0 的所有 id, 一般做法是使用filter + map, 使用 reduce 的话可以更高效
const arr = [
    { id: '1', status: 1 },
    { id: '2', status: 0 },
    { id: '3', status: 0 },
    { id: '4', status: 1 }
]

// 使用 filter + map
const ids1 = arr.filter(v => v.status === 0).map(v => v.id) 

// 使用 reduce
const ids2 = arr.reduce((t, v) => {
    if (v.status === 0) t.push(v.id)
    return t
}, [])