### `reduce()`

reduce() 函数接收2个参数(M: 必填, O: 可选)：

• (M) 回调reducer 函数 处理先前的结算结果和下一个元素直到序列结束。
• (O) 初值 作为第一次调用回调时的第一个参数。

### 普通用法 (累加，关联)

``````// 当前的购物清单
var items = [{price: 10}, {price: 120}, {price: 1000}];

// reducer函数
var reducer = function add(sumSoFar, nextPrice) { return sumSoFar + nextPrice.price; };

// 开始运行
var total = items.reduce(reducer, 0);

console.log(total); // 1130
``````

`reduce`函数可选的参数在第一个例子里是基本变量数字0，但是它也可以是一个对象，数组… 而不仅是基本类型，之后我们将会看到。

``````var total = items.reduce(reducer,-20);

console.log(total); // 1110
``````

### 进阶用法(结合)

``````var reducers = {
totalInDollar: function(state, item) {
state.dollars += item.price;
return state;
},
totalInEuros : function(state, item) {
state.euros += item.price * 0.897424392;
return state;
},
totalInPounds : function(state, item) {
state.pounds += item.price * 0.692688671;
return state;
},
totalInYen : function(state, item) {
state.yens += item.price * 113.852;
return state;
}
// more...
};
``````

• 能够调用每一部分的`reduce`函数
• 返回一个新的`reducer`回调函数
``````var combineTotalPriceReducers = function(reducers) {
return function(state, item) {
return Object.keys(reducers).reduce(
function(nextState, key) {
reducers[key](state, item);
return state;
},
{}
);
}
};
``````

``````var bigTotalPriceReducer = combineTotalPriceReducers(reducers);

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

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

console.log(totals);

/*
Object {dollars: 1130, euros: 1015.11531904, yens: 127524.24, pounds: 785.81131152}
*/
``````