
▶️四个参数
- Accumulator (acc) (累计器)
- Current Value (cur) (当前值)
- Current Index (idx) (当前索引)
- Source Array (src) (源数组)
reducer 函数的返回值分配给累计器,并最后成为最终的单个结果值。
▶️ reduce如何运行
假如运行下段reduce()代码:
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
return accumulator + currentValue;
});
callback 被调用四次,每次调用的参数和返回值如下表:
没有默认值
callbackaccumulatorcurrentValuecurrentIndexarrayreturn valuefirst call011[0, 1, 2, 3, 4]1second call122[0, 1, 2, 3, 4]3third call333[0, 1, 2, 3, 4]6fourth call644[0, 1, 2, 3, 4]10
由reduce返回的值将是最后一次回调返回值(10)。
你同样可以使用箭头函数的形式,下面的代码会输出跟前面一样的结果
您还可以提供Arrow Function 来代替完整的函数。 下面的代码将产生与上面的代码中相同的输出:
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue; }, 10 );
如果你打算提供一个初始值作为reduce()方法的第二个参数,以下是运行过程及结果:
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue; }, 10 );
有默认值
这种情况下reduce()返回的值是20。
▶️用例
- 数组求和;
- 对象数组根据属性分类,或者求值;
- 数组去重或者数组元素统计;
- 将二维数组转化成一维;(1.使用concat;2.[...arr1 , ...arr2]);
- 按顺序运行promise;
// Building-blocks to use for composition
const double = x => x + x;
const triple = x => 3 * x;
const quadruple = x => 4 * x;
// Function composition enabling pipe functionality
const pipe = (...functions) => input => functions.reduce(
(acc, fn) => fn(acc),
input
);
// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);
// Usage
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240
- 功能性函数管道;
// Building-blocks to use for composition
const double = x => x + x;
const triple = x => 3 * x;
const quadruple = x => 4 * x;
// Function composition enabling pipe functionality
const pipe = (...functions) => input => functions.reduce(
(acc, fn) => fn(acc),
input
);
// Composed functions for multiplication of specific values
const multiply6 = pipe(double, triple);
const multiply9 = pipe(triple, triple);
const multiply16 = pipe(quadruple, quadruple);
const multiply24 = pipe(double, triple, quadruple);
// Usage
multiply6(6); // 36
multiply9(9); // 81
multiply16(16); // 256
multiply24(10); // 240
<p data-line="114" class="sync-line" style="margin:0;"></p>
- 使用 reduce实现map;
未完待续。。。
胜象大百科







