关于Array.reduce()的使用
API
reduce() 方法对累加器和数组中的每个元素(从左到右)应用一个函数,将其减少为单个值。
使用用法参考这个连接就可以Array.prototype.reduce().
应用场景
当我们处理累加这样的业务时候就要想到使用reduce.
// 计算所有购买的物品总价格.
var items = [{price: 10}, {price: 120}, {price: 1000}];
// our reducer function(callback)
var reducer = function add(sumSoFar, item) { return sumSoFar + item.price; };
// do the job
var total = items.reduce(reducer, 0);
// 如果你有优惠券之类的
var discount = xxxx; // 计算后的优惠价格
var total = items.reduce(reducer, discount);
console.log(total); // 1130
上述只是reduce的常规使用. 下面是更加复杂的需求.
// 计算所有购买的物品总价格. 但是需要考虑不同的货币
var items = [{price: 10}, {price: 120}, {price: 1000}];
var reducers = {
// 美元结算
totalInDollar: function(state, item) {
// specific statements...
return state.dollars += item.price;
},
// 欧元结算
totalInEuros : function(state, item) {
return state.euros += item.price * 0.897424392;
},
// 英镑
totalInPounds : function(state, item) {
return state.pounds += item.price * 0.692688671;
},
// 日元
totalInYen : function(state, item) {
return state.yens += item.price * 113.852;
}
// more...
};
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); // { dollars: 1130, euros: 1014.08956296, yens: 128652.76, pounds: 782.73819823 }
上述的例子借鉴于Redux combineReducers function。一个reduces可以是包含很多不同功能的reduce.