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
CodeRookie262 opened this issue Dec 31, 2020 · 2 comments
Open

实现 Array.prototype.reduce 方法 #13

CodeRookie262 opened this issue Dec 31, 2020 · 2 comments
Labels

Comments

@CodeRookie262
Copy link
Owner

根据 Array.prototype.reduce 的特性进行封装

Link:特性

@CodeRookie262
Copy link
Owner Author

/**
 *
 * @param {Function} callback
 *  callback 可接收4个参数
 * - accumulator - 累计器累计回调的返回值;
 * - currentValue - 数组中正在处理的元素;
 * - index? - 数组中正在处理的当前元素的索引;
 * - array? - 源数组;
 *
 * @param {any} [initialValue]
 *  作为第一次调用 callback函数时的第一个参数的值。
 *  如果没有提供初始值,则将使用数组中的第一个元素。
 *  在没有初始值的空数组上调用 reduce 将报错。
 */
function customReduce(callback, initialValue) {
  let context = this; //获取数组
  if (context.length === 0) throw new Error('TypeError: 数组长度不能为 0');
  let hasInit = typeof initialValue === 'undefined'; //判断是否有初始值

  for (var i = hasInit ? 1 : 0; i < context.length; i++) {
    initialValue = callback(
      hasInit ? context[i] : initialValue,
      context[i],
      i,
      context
    );
  }

  return initialValue;
}

Array.prototype.customReduce = customReduce;

@jiawood
Copy link

jiawood commented Mar 30, 2022

customReduce实现有点小问题哈

function customReduce(callback, initialValue) {
  let context = this; //获取数组
  if (context.length === 0) throw new Error('TypeError: 数组长度不能为 0');
  let hasInit = typeof initialValue === 'undefined'; //判断是否有初始值

  for (var i = hasInit ? 1 : 0; i < context.length; i++) {
    initialValue = callback(
      hasInit ? context[0] : initialValue,
      context[i],
      i,
      context
    );
    hasInit = false  
  }

  return initialValue;
}

Array.prototype.customReduce = customReduce;

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

No branches or pull requests

2 participants