TS实现原生数组方法之遍历:reduce()

/**
 * @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)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值