定义:
reduce()方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最后计算为一个值
reduce()可以作为一个高阶函数,用于函数的compose
*注意:reduce()对于空数组是不会执行回调函数的
例子:
计算数组元素的总和
var numbers = [1, 2, 3, 4];
function getSum(total, num) {
return total + num;
}
console.log(getSum()) // 10
语法:
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数:
total:必填,初始值,或者计算后的返回值
currentValue:必填,当前元素
currentIndex:可选,当前元素的索引
arr:可选,当前元素所属的数组对象
initialValue:可选,传给函数的初始值
例子:
const assessTypeOptions = [
{status:0,name:'评估中'},
{status:1,name:'评估完成'}
]
const assessTypeKeyValue = assessTypeOptions.reduce((acc, cur) => {
acc[cur.status] = cur.name
return acc
}, {})
console.log(assessTypeKeyValue[0]) //评估中
例子:二维数组处理结果为对象
let arr = [
['红色','黑色','白色'],
['16G','32G'],
['移动版','联通版']
]
结果:
[ {'attr0': '红色', 'attr1':'16G', 'attr2':'移动版' },
{'attr0': '红色', 'attr1':'16G', 'attr2':'联通版' },
{'attr0': '红色', 'attr1':'32G', 'attr2':'移动版' },
{'attr0': '红色', 'attr1':'32G', 'attr2':'联通版' },
{'attr0': '黑色', 'attr1':'16G', 'attr2':'移动版' },
{'attr0': '黑色', 'attr1':'16G', 'attr2':'联通版' },
{'attr0': '黑色', 'attr1':'32G', 'attr2':'移动版' },
{'attr0': '黑色', 'attr1':'32G', 'attr2':'联通版' },
{'attr0': '白色', 'attr1':'16G', 'attr2':'移动版' },
{'attr0': '白色', 'attr1':'16G', 'attr2':'联通版' },
{'attr0': '白色', 'attr1':'32G', 'attr2':'移动版' },
{'attr0': '白色', 'attr1':'32G', 'attr2':'联通版' }
]
let arr = [
['红色','黑色','白色'],
['16G','32G'],
['移动版','联通版']
]
//reduce
let s = arr.reduce( (res,current,index)=>{
//第一个数组
if(index == 0) {
current.forEach(ele=>{
res.push({['attr' + index] : ele })
})
} else {
//其他数组
let newArr=[]
res.forEach(obj=>{
current.forEach(ele=>{
// console.info({ ...obj, ['attr'+index] : ele})
newArr.push({ ...obj, ['attr' +index] : ele})
})
})
res = newArr
}
return res
} , [])
console.info(s)

本文介绍了JavaScript中的reduce方法,用于计算数组元素的总和,并展示了如何使用reduce进行对象构建和二维数组处理。通过示例详细解释了reduce参数及工作原理,包括初始值设置和回调函数的运用。同时,提供了将二维数组转换为特定格式的对象数组的代码实现。

528

被折叠的 条评论
为什么被折叠?



