js 实现Array.prototype.reduce方法
Array.prototype.my_reduce = function(callBack, initValue) {
if (typeof callBack !== 'function') { // 方法错误处理
throw new Error(`${callBack} is not a function`)
}
const me = this // 获取当前数组
const startIndex = initValue ? 0 : 1 // 如果有 initValue 就对数组进行全循环,否则就从数组第一项循环
let result = initValue ? initValue : me[0] // 如果有 initValue 就将 initValue 作为数组的第一项 否则就取数组的第一项
for (let i = startIndex; i < me.length; i++) {
result = callBack(result, me[i], i , me) // 循环执行回调方法,将上一次的结果当做回调的第一个参数传入
}
return result // 返回最终计算结果
}
下面验证一下
const res = arr.my_reduce((pre, item) => {
return pre + item
})
console.log(res)
const res = arr.my_reduce((pre, item) => {
return pre + item
}, 2)
console.log(res)
作者:毛小星
本文版权归作者和博客园共有,欢迎转载,转载请标明出处