原生reduce接收几个参数?
- 一个回调函数。这个回调函数的前两个参数,分别表示累积值和当前值。
- 初始值。
实现原生reduce的思路
- 通过slice原型方法获取到调用reduce的数组。
- 定义一个临时结果变量和开始的索引。
- 如果传入了初始值,res就等于这个初始值,没有传入res就等于数组的第一项。
- 如果传入了初始值,起始索引就是0,没有传入起始所以就是1,这里的1代表的是数组的第二项。
- 从起始下标开始遍历,res = fn.call(null,res,arr[i])
Array.prototype.myReduce = function (fn, initialValue) {
var arr = Array.prototype.slice.call(this);
var res, startIndex;
res = initialValue ? initialValue : arr[0];
startIndex = initialValue ? 0 : 1;
for (var i = startIndex; i < arr.length; i++) {
res = fn.call(null, res, arr[i]);
}
return res;
}
const test = [1,2,3];
console.log(test.myReduce((pre,cur) => pre + cur));
总结与思考