reduce: "缩减"
含义:arr.reduce() 将数组中的每个值(从左到右)开始缩减,最终计算为一个值。
语法: arr.reduce()会对数组中每一项运行回调函数,返回最后一次回调函数的执行结果。
arr.reduce((total, currentValue, index, arr) => {}, initialValue)
total 是初始值,或者计算结束后的返回值。这个值初始值是0
currentValue 当前元素
index currentValue在数组中的下标
arr 调用reduce()方法的数组
问:如果initailValue 不定义,一开始初始的值默认是什么? 答:0
案例
求和:
const arr = [1, 2, 3, 4]
const sum = arr.reduce((x, y) => x + y)
console.log(sum) // 10
const arr = [1, 2, 3, 4]
const sum = arr.reduce((x, y) => x + y, 10)
console.log(sum) // 20
求积:
上面例子 + 改成 *
高级用法
(1) 计算数组中每个元素出现的次数
const sum = arr.reduce((x, y) => {
if (y in x) {
x[y]++
} else {
x[y] = 1
}
return x
}, {})
console.log(sum) // { 1: 2, 2: 1, 3: 1, 4: 1 }
(2) 数组去重
const arr = [1, 2, 3, 4, 1]
const sum = arr.reduce((x, y) => {
if (!x.includes(y)) {
return x.concat(y)
} else {
return x
}
}, [])
console.log(sum)
(3) 将数组转换成map对象
const a = [1, 2, 3], b = [3, 4, 5]
const map = b.reduce((r, item) => (r[item] = true, r), {}) // 通过reduce把b转换成map对象
console.log(a.some(v => map[v])) // 判断a和b的交集
手写系列
手写实现reduce
Array.prototype.myReduce = function (cb, initialValue) {
let total = initialValue || this[0
let start = initialValue ? 0 : 1
for (let i = start; i < this.length; i++) {
total = cb(total, this[i])
}
return total
}