为什么reduceRight在Javascript中返回NaN?

时间:2010-01-22 15:07:06

标签: javascript firefox functional-programming reduce

我正在使用Firefox 3.5.7并且在Firebug中我试图测试array.reduceRight函数,它适用于简单数组但是当我尝试这样的东西时我得到了一个 NaN的即可。为什么呢?

>>> var details = [{score : 1}, {score: 2}, {score: 3}];
>>> details
[Object score=1, Object score=2, Object score=3]
>>> details.reduceRight(function(x, y) {return x.score + y.score;}, 0)
NaN

我也试过map,至少我可以看到每个元素的.score组件:

>>> details.map(function(x) {console.log (x.score);})
1
2
3
[undefined, undefined, undefined]

我在https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight阅读了文档,但显然我无法在详细信息数组中总结所有得分值。为什么呢?

3 个答案:

答案 0 :(得分:7)

赋予函数的第一个参数是累计值。因此,对函数的第一次调用看起来像f(0, {score: 1})。所以当做x.score时,你实际上做的是0.score当然不起作用。换句话说,你想要x + y.score

答案 1 :(得分:4)

试试这个(将转换为数字作为副作用)

details.reduceRight(function(previousValue, currentValue, index, array) {
  return previousValue + currentValue.score;
}, 0)

或者

details.reduceRight(function(previousValue, currentValue, index, array) {
  var ret = { 'score' : previousValue.score + currentValue.score} ;
  return ret;
}, { 'score' : 0 })

感谢@ sepp2k指出如何将{ 'score' : 0 }作为参数。

答案 2 :(得分:0)

reduce函数应该将具有属性“score”的两个对象组合到具有属性“score”的新对象中。你把它们组合成一个数字。