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.
本文详细解析了ArrayReduce函数的基本用法及一个常见错误案例。通过对比正确的与错误的使用方式,强调了如何避免在处理对象数组时出现null值的问题。
250

被折叠的 条评论
为什么被折叠?



