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

数组reduce方法模拟实现 #38

Open
conan1992 opened this issue Jun 24, 2020 · 0 comments
Open

数组reduce方法模拟实现 #38

conan1992 opened this issue Jun 24, 2020 · 0 comments

Comments

@conan1992
Copy link
Owner

reduce

reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

参数

  • callback
    执行数组中每个值 (如果没有提供 initialValue则第一个值除外)的函数,包含四个参数
    • accumulator
      累计器累计回调的返回值; 它是上一次调用回调时返回的累积值,或initialValue(见于下方)。
    • currentVlaue
      数组中正在处理的元素。
    • index(可选)
      数组中正在处理的当前元素的索引。 如果提供了initialValue,则起始索引号为0,否则从索引1起始
    • array(可选)
      调用reduce()的数组
Array.prototype.reduce2 = function(fn, initialValue){
    var O = Object(this)
    var len = this.length;
    var acc = initialValue || O[0];
    var i = initialValue ? 0 : 1;
    for(;i<len;i++){
        acc = fn(acc, O[i], i, O)
    }

    return acc;
}
let nums = [1, 2, 3];
let obj = {val: 5};
let result = nums.reduce2(function(acc, cur, index,array) {
  return acc + cur; 
}, 1);
console.log(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