Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array.prototype.reduce #13

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

Array.prototype.reduce #13

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

Array.prototype.myReduce = function (callback, ...args) {
  let start = 0,
    pre;
  if (args.length) {
    //有参数的话pre等于参数第0项
    pre = args[0];
  } else {
    //没参数的话,默认从数组0项开始
    pre = this[0];
    start = 1;
  }
  for (let i = start; i < this.length; i++) {
    pre = callback(pre, this[i], i, this);
  }
  return pre;
};
@hannah-bingo
Copy link
Contributor

     Array.prototype.reduce = function(fn,initValue) {
            let result = initValue === undefined ? this[1] : initValue;
            for(let i = 0; i<this.length ;i++) {
                result = fn(result, this[i], i, this)
            }
            return result;
        }

关于reduce的用法

@kangkang123269
Copy link

kangkang123269 commented Feb 20, 2023

  1. 使用方法
array.reduce(function(accumulator, currentValue, index, array) {
  // return updated accumulator
}, initialValue)

其中,参数 function(accumulator, currentValue, index, array) 是一个回调函数,用于处理每个数组元素并更新累加器的值。回调函数接受四个参数:

  • accumulator: 累加器的值,初始值为 initialValue
  • currentValue: 当前数组元素的值
  • index: 当前数组元素的索引
  • array: 原始数组
  1. 实现方法
Array.prototype.reduce = function(callback, initialValue) {
  var accumulator = (initialValue !== undefined) ? initialValue : this[0];
  for (var i = (initialValue !== undefined) ? 0 : 1; i < this.length; i++) {
    accumulator = callback.call(undefined, accumulator, this[i], i, this);
  }
  return accumulator;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants