Array Reduce 的用法已经在spec里讲的很清楚了,基本用法如下:
[0,1,2,3,4].reduce(function(previousValue, currentValue, index, array){
return previousValue + currentValue;
});
回调被执行四次,每次的参数和返回值如下表:
previousValue | currentValue | index | array | return value | |
---|---|---|---|---|---|
first call | 0 | 1 | 1 | [0,1,2,3,4] | 1 |
second call | 1 | 2 | 2 | [0,1,2,3,4] | 3 |
third call | 3 | 3 | 3 | [0,1,2,3,4] | 6 |
fourth call | 6 | 4 | 4 | [0,1,2,3,4] | 10 |
reduce
的返回值是回调函数最后一次被调用的返回值(10)。
但是有一次用的时候还是出了问题:
var Array = [{count: 10 , user_id: 'zhangziyi'}, {count: 100, user_id: 'Angelababy'}];
array.reduce(function(x,y){ return x.count + y.count;});
这个写法看似正确的,执行也能得到正确的结果:110。 但是如果数组有3个以上的数据,执行这个结果变成了Null.
var Array = [{count: 10 , user_id: 'zhangziyi'}, {count: 100, user_id: 'Angelababy'}, {count: 140 , user_id: 'Zhaowei'}];
array.reduce(function(x,y){ return x.count + y.count;});仔细研究发现这执行的是一下情况:
第一次: return : x.count + y.count = 10+100=110;
第二次: return: 110.count + 140 =null;;
所以对象元素使用reduce正确的做法应该是:
var countObj = array.reduce(function(x,y){ var temp = {}; temp.count = x.count + y.count; return temp });执行完了,取出数据即可:
var total = countObj.count;
这样就得到了想要的结果: 250.