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

第 26 期(ECMAScript-原型链 继承):实现 Array reduce #29

Open
wingmeng opened this issue Jun 4, 2019 · 0 comments
Open

第 26 期(ECMAScript-原型链 继承):实现 Array reduce #29

wingmeng opened this issue Jun 4, 2019 · 0 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented Jun 4, 2019

题目:

请编写一个方法 reduceArr,实现与 ES5 规范中数组的 reduce 方法同样的功能

相关: 第 22 期(ECMAScript-原型链 继承):实现 Array map

测试用例:

var data = [1, 2, 3, 4];

var result1 = data.reduceArr(function(total, cur, idx, arr) {
  return total + cur;
});

var result2 = data.reduceArr(function(total, cur, idx, arr) {
  return total + cur;
}, 100);

console.log(result1);  // 10
console.log(result2);  // 110

参考答案:

Array.prototype.reduceArr = function(fn, initialVal) {
  var arr = this;
  var result = arr[0];
  var startIdx = 1;
  
  if (typeof initialVal !== 'undefined') {
    result = initialVal;
    startIdx = 0;
  }

  for (var i = startIdx; i < arr.length; i++) {
    result = fn(result, arr[i], i, arr);
  }

  return result;
};
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

1 participant