1

我正在使用 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上的文档,但显然我无法汇总我的详细信息数组中的所有分数值。为什么?

4

3 回答 3

7

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

于 2010-01-22T15:14:39.830 回答
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 }需要如何作为参数。

于 2010-01-22T15:11:20.460 回答
0

reduce 函数应该将两个具有属性“score”的对象组合成一个具有属性“score”的新对象。您正在将它们组合成一个数字。

于 2010-01-22T15:12:58.720 回答