arr.reduce ( function (PREV, CUR, index, ARR) { ... }, the init);
// ARR represents the original array;
// PREV represents the return value of the callback time of the last call, or the initial value of the init;
// cur represents the array element currently being processed;
// index represents the index of the array element currently being processed, if provided init value, then the index is 0, or index. 1;
// init represents an initial value.
reduce () method takes a function as an accumulator, each value in the array (left to right) started to shrink, as a final calculated value.
reduce () function as a higher order, for compose function.
Note: the reduce () for an empty array will not be implemented callback function.
expand:
1 去 重
const newArr = arr.reduce(function (prev, cur) { prev.indexOf(cur) === -1 && prev.push(cur); return prev; },[]);
2 最值
const max = arr.reduce(function (prev, cur) {
return Math.max(prev,cur);
});
3 求和
const sum = arr.reduce(function (prev, cur) {
return prev + cur;
},0);