reduce 函数

const reduce = (arr, fn) => {
  let sum = 1;
  arr.map(r => (sum = fn(sum, r)));
  return sum;
};
const a = [1, 4, 3];

//  抽象部分
const b = reduce(a, (acc, value) => acc * value);
const c = reduce(a, (acc, value) => acc + value);

console.log(b);  // 12
console.log(c);  //  8

你可能感兴趣的:(reduce 函数)