这是我参与更文挑战的第1天,活动详情查看: 更文挑战。
作为一只白了又白的小白,在了解reduce之前,我们先看个在实际开发中遇到的例子
suc是我们从后端取到的一个二维循环数组
例子
suc.list.reduce((pre, cur) => {
idlis.push(cur.status)
if (cur.status == 10 || cur.status == 20) {
复制代码
idlist.push(cur)
} else if (cur.status == 30 || cur.status == 40) {
idlists.push(cur)
} else if (cur.status == 50 || cur.status == 60) {
idslists.push(cur)
}
}, [])
显然,上面的效果和下面的一样
for (let i = 0; i < suc.list.length; i++) {
复制代码
if (suc.list[i].status == 10 || suc.list[i].status == 20) {
this.listUndoData.push(suc.list[i])
复制代码
} else if (suc.list[i].status == 30 || suc.list[i].status == 40) {
this.listDoingData.push(suc.list[i])
复制代码
} else if (suc.list[i].status == 50 ||suc.list[i].status == 60) {
this.listDoneData.push(suc.list[i])
复制代码
}
}
复制代码
我们都是将suc.list中的status取出来作比较,再根据status的值分类通过push添加到不同的数组中。
很明显,使用reduce比for循环更优
reduce的定义
reduce()方法是对数组中的每个元素执行一个由自身提供的reducer函数(升序执行),并将其结果汇总为单个返回值。
复制代码
语法:
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
复制代码
函数接收4个参数:
Accumulator (acc) (累计器)
Current Value (cur) (当前值)
Current Index (idx) (当前索引)
Source Array (src) (源数组)
参数:
callback`
执行数组中每个值 (如果没有提供 initialValue则第一个值除外
)的函数,包含四个参数:
**accumulator
**累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue
(见于下方)。currentValue
数组中正在处理的元素。index
可选数组中正在处理的当前元素的索引。 如果提供了initialValue
,则起始索引号为0,否则从索引1起始。array
可选调用reduce()
的数组
initialValue`可选
作为第一次调用 callback
函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。
注意:reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值并返回。
reduce() 可以作为一个高阶函数,用于函数的 compose。
且:** reduce() 对于空数组是不会执行回调函数的。**
由上面的例子,我们不由得开始想,reduce实现的功能既然for循环可以实现,那我们使用reduce是为什么呢?
首先,我们从写法上可以看出,和for循环相比,reduce的写法更为简洁,也更显高级。
同时,reduce可以求和,去重,多维转化为一维