每次看到這個api ,就有點發(fā)懵,今天詳細解析下此屬性匀泊。還是先看官方文檔吧:
Reduce方法對數(shù)組中的每個元素執(zhí)行一個由您提供的reducer函數(shù)(升序執(zhí)行),將其結(jié)果匯總為單個返回值。
reducer 函數(shù)接收4個參數(shù):
Accumulator (acc) (累計器)
Current Value (cur) (當(dāng)前值)
Current Index (idx) (當(dāng)前索引)
Source Array (src) (源數(shù)組)
您的 reducer 函數(shù)的返回值分配給累計器冒萄,該返回值在數(shù)組的每個迭代中被記住萎河,并最后成為最終的單個結(jié)果值荔泳。
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
nitialValue可選
作為第一次調(diào)用 callback函數(shù)時的第一個參數(shù)的值蕉饼。 如果沒有提供初始值,則將使用數(shù)組中的第一個元素玛歌。 在沒有初始值的空數(shù)組上調(diào)用 reduce 將報錯昧港。
項目中的運用
histryFilters: histryList.filterList.reduce((obj, item) => {
if (item.type !== 'button') {
obj[item.key] = ''
}
return obj
}, {}),
filters: list.filterList.reduce((obj, item) => {
if (item.type !== 'button') {
obj[item.key] = ''
}
return obj
}, {}),
const keyValueMap = totalMap.reduce((e, i) => {
e[i.value] = i.label
return e
}, {})