??四個參數
- 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;
未完待續。。。