JavaScript的reduce和reduceRight的作用是通过顺序或逆序遍历数组,从而得到一个结果,原理如下:
function myReduce(execute, initValue) {
const length = this.length
let result
for (let i = 0; i < length; i++) {
if (i === 0) {
const hasInitValue = initValue !== void 0,
startIndex = hasInitValue ? 0 : 1
i = startIndex
result = execute(hasInitValue ? initValue : this[0], this[i], i, this)
} else {
result = execute(result, this[i], i, this)
}
}
return result
}
function myReduceRight(execute, initValue) {
const length = this.length
let result
for (let i = length - 1; i >= 0; i--) {
if (i === length - 1) {
const hasInitValue = initValue !== void 0,
startIndex = hasInitValue ? length - 1 : length - 2
i = startIndex
result = execute(hasInitValue ? initValue : this[length - 1], this[i], i, this)
} else {
result = execute(result, this[i], i, this)
}
}
return result
}
Array.prototype.myReduce = myReduce
Array.prototype.myReduceRight = myReduceRight
案例01——累加
array.myReduce(function (pre, cur, index, context) {
return pre + cur
})
案例02——统计
array.myReduce(function (pre, cur, index, context) {
if (pre[cur]) {
pre[cur]++
} else {
pre[cur] = 1
}
return pre
}, {})
案例03——扁平化
array.myReduce(function (pre, cur, index, context) {
if (Array.isArray(cur)) {
pre.splice(pre.length, 0, ...cur)
} else {
pre.push(cur)
}
return pre
}, [])
案例04——去重
array.myReduce(function (pre, cur, index, context) {
if (pre.includes(cur)) {
return pre
} else {
pre.push(cur)
}
return pre
}, [])
案例05——最值
array.myReduce(function (pre, cur, index, context) {
return Math.min(pre, cur)
})
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。