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 #17

Open
nmsn opened this issue Nov 21, 2022 · 2 comments
Open

实现 Array.prototype.reduce #17

nmsn opened this issue Nov 21, 2022 · 2 comments

Comments

@nmsn
Copy link
Contributor

nmsn commented Nov 21, 2022

如题

@nmsn
Copy link
Contributor Author

nmsn commented Nov 23, 2022

Array.prototype._reduce = function (exc, initial = 0) {
  let result = initial;
  this.forEach((item) => {
    result = exc(result, item);
  });
  return result;
}

@nmsn
Copy link
Contributor Author

nmsn commented May 22, 2023

Array.prototype._reduce = function (fn, prev) {
  if (typeof fn !== 'function') return

  for (let i = 0; i < this.length; i++) {
    // 如果不传递prev,那么第一次调用时传递的初始参数就默认为数组的第一个元素,累加元素为数组索引为1处的元素
    if (prev === undefined) {
      prev = fn(this[i], this[i + 1], i + 1, this)
      // 此时i为1,但是下一次要从索引为2处开始加,所以这里i++
      i++
    } else {
      // 如果传递了初始参数,那么传递对应参数即可
      prev = fn(prev, this[i], i, this)
    }
  }
  // 最后返回prev,prev是一个元素,但不限类型,可能为数组,对象,数字等
  return prev
}

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

No branches or pull requests

1 participant