/**
* @function Array.prototype.reduce
* @description 数组中的每个元素按序执行一个 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
* @param callbackfn callbackfn.上一次调用 callbackFn 时的返回值.2.当前正在处理的元素(可选)3.当前索引值(可选)4.用于遍历的数组
* @param initialValue 可选参数,第一次调用的初始值,若指定该值,则callbackfn第一个参数为initialValue,从第0个元素开始遍历,否则初始值为arr[0],从第一个元素开始遍历,
*/
/** @ts-ignore */
Array.prototype.reduce = function (callbackfn: (previousValue: any, currentValue: any, currentIndex: number, array: any[]) => any, initialValue: any): any {
// null | undefined 不能调用方法
if ((!this && typeof this === 'object') || typeof this === 'undefined') {
throw new Error(`Uncaught TypeError: Cannot read properties of ${this}`);
};
if (typeof callbackfn !== 'function') {
throw new Error(`${callbackfn} is not a function`)
}
// 获取数组
const arr = Object(this);
if (arr.length === 0 && typeof initialValue === 'undefined') {
throw new Error(`Uncaught TypeError: 数组为空且未指定初始值 initialValue`);
}
const _len = arr.length;
let result = typeof initialValue === 'undefined' ? arr[0] : initialValue;
let i = typeof initialValue === 'undefined' ? 1 : 0;
for (i; i < _len; i++) {
result = callbackfn.call(this, result, arr[i], i, arr);
}
return result;
}
// test data
const forArr = [1, 2, 3, 4, 5];
const redulesum_none = forArr.reduce(function (previousValue, currentValue) {
return previousValue + currentValue
});
const redulesum = forArr.reduce(function (previousValue, currentValue) {
return previousValue + currentValue
}, 100);
console.log(redulesum_none, redulesum)
TS实现原生数组方法之遍历:reduce()
最新推荐文章于 2024-05-06 09:01:42 发布