你需要传入一个回调函数作为参数。
- 第一个参数:回调函数接收四个参数:累加器(accumulator)、当前值(current value)、当前索引(current index)和数组本身(array)。回调函数返回的结果将作为下一次迭代的累加器值。
- 第二个初始值,没有默认 arr[0]
自定义实现
var myReduce = function(callback, initialValue) {
if (this.length === 0 && initialValue === undefined) {
throw new TypeError("Reduce of empty array with no initial value");
}
if(typeof callback !== 'function') {
throw new TypeError(" error");
}
let accumulator = initialValue !== undefined ? initialValue : this[0];
for (let i = initialValue !== undefined ? 0 : 1; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
}
return accumulator;
};
reduce 实现map
var myMap = function(fn, context) {
if(typeof callback !== 'function') {
throw new TypeError(" error");
}
let res = [];
let _ctx = context || null;
this.reduce((prev, cur, idx, arr) => {
res.push(fn.call(_ctx, cur, idx, arr));
}, null);
return res;
};