reduce屬於javascript「synchronize 同步」的array method,他就是把一整個array的所有內容,有順序性的擠壓squeeze
最後變成一個值
[1,2,3,4].reduce((accumulator, currentValue) => {
//call back要做的動作,最後變成一個值
}, initValue)
//accumulator = 積累
//for迴圈將陣列內容依序一個一個的帶進來
const reduceFunc = (reducer, initVal, dataArray) => {
let val = initVal;
for(const i in dataArray) {
val = reducer(val, dataArray[i]);
}
return val;
}
reduceFunc((acc, current) => (acc + current), 0, [1, 2, 3, 4])
// 10
以上範例是拆解reduce的工作,簡單來說一開始先拿到初始值initValue,然後用for迴圈一個一個的帶進去reducer(val, dataArray[i]),acc的初始值是initVal接著的每一次for迴圈acc都會是前一次結果的值,過程順序如下:
//acc = 0, current = 1, val = 1
//acc = 1, current = 2, val = 3
//acc = 3, current = 3, val = 6
//acc = 6, current = 4, val = 10
Reduce不是遞迴而是for迴圈