📜  stackoverflow 数组 reduce - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:01:34.946000             🧑  作者: Mango

代码示例1
const arr = [{x:1}, {x:2}, {x:4}];
arr.reduce(function (acc, obj) { 
    return acc + obj.x; 
  }, 0); //result = 7

// acc = accumulator (result from the last iteration)
// obj = iterated object from arr
// 0 = initial value for the accumulator(acc)

// Arrow function =>
arr.reduce((acc, obj) => acc + obj.x, 0);

// 0 + 1 = 1 
// 1 + 2 = 3 
// 3 + 4 = 7;
// *note when multiplying use a initial value of 1 
// beceause => (0 * 2 = 0)