一、reduce方法
array.reduce(function(previous, currentValue, currentIndex, arr), initialValue)
参数 | 描述 |
previous | 初始值,必传参数 |
currentValue | 当前元素,必传参数 |
currentIndex | 当前元素索引值 |
arr | 数组 |
initialValue:传递给函数的初始值,如果传了previous初始值为initialValue传的值,currentValue为数组的第一个元素,如果不传previous为数组的第一个元素,currentValue为数组的第二个元素
二、reduce的用法
const arr: any = [
{ label: '1', value: '1' },
{ label: '2', value: '22' },
{ label: '3', value: '333' },
{ label: '4', value: '4444' },
{ label: '5', value: '55555' },
{ label: '6', value: '666666' },
];
const newArr = arr.reduce((pre: any, cur: any, index: any) => {
pre[cur.value] = index;
return pre;
}, {});
console.log(newArr);
//输出结果
{
"1": 0,
"22": 1,
"333": 2,
"4444": 3,
"55555": 4,
"666666": 5
}