reduce方法的应用

数组的reduce方法的应用

var items = [10, 120, 1000];

var reducer = function add(sumSoFar, item) { return sumSoFar + item; };

var total = items.reduce(reducer, 0);

console.log(total); // 1130

数组的reduce方法的应用(初始值为object类型)

var items = [10, 120, 1000];

var reducer = function add(sumSoFar, item) {
  sumSoFar.sum = sumSoFar.sum + item;
  return sumSoFar;
};

var total = items.reduce(reducer, {sum: 0});

console.log(total); // {sum:1130}

多重叠加

var reducers = {  
  totalInEuros : function(state, item) {
    return state.euros += item.price * 0.897424392;
  },
  totalInYen : function(state, item) {
    return state.yens += item.price * 113.852;
  }
};

var manageReducers = function(reducers) {
  return function(state, item) {
    return Object.keys(reducers).reduce(
      function(nextState, key) {
        reducers[key](state, item);
        return state;
      },
      {}
    );
  }
};

var bigTotalPriceReducer = manageReducers(reducers);

var initialState = {euros:0, yens: 0};

var items = [{price: 10}, {price: 120}, {price: 1000}];

var totals = items.reduce(bigTotalPriceReducer, initialState);

console.log(totals);
JSRUN notes