Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/371.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为什么reduceRight在Javascript中返回NaN?_Javascript_Firefox_Functional Programming_Reduce - Fatal编程技术网

为什么reduceRight在Javascript中返回NaN?

为什么reduceRight在Javascript中返回NaN?,javascript,firefox,functional-programming,reduce,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.redu

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

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

还是这个

details.reduceRight(function(previousValue, currentValue, index, array) {
  var ret = { 'score' : previousValue.score + currentValue.score} ;
  return ret;
}, { 'score' : 0 })
感谢@sepp2k指出如何将
{'score':0}
用作参数。

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

还是这个

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

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

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

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

函数的第一个参数是累积值。因此,对该函数的第一次调用将类似于
f(0,{score:1})
。所以当你做x.score的时候,你实际上是在做0.score,这当然不起作用。换句话说,您需要
x+y.score

函数的第一个参数是累积值。因此,对该函数的第一次调用将类似于
f(0,{score:1})
。所以当你做x.score的时候,你实际上是在做0.score,这当然不起作用。换句话说,您需要
x+y.score

,因此基本上,当您将初始值传递给reduceRight时,它的行为就像一个折叠。我没有意识到这一点。所以基本上,当你把初始值传递给reduceRight时,它表现为折叠。我没有意识到这一点。函数应该将a类型的对象和b类型的对象(其中a是初始值的类型,b是数组的元素类型)组合成a类型的对象。a和b不一定是同一类型的。是的,我知道。我主要使用Scala,其中reduce操作总是生成与输入列表类型相同的值。在Scala中,将列表中的值累加成另一种类型的值的操作称为fold。该函数应将类型a的对象和类型b的对象(其中a是初始值的类型,b是数组的元素类型)组合成类型a的对象。a和b不一定是同一类型的。是的,我知道。我主要使用Scala,其中reduce操作总是生成与输入列表类型相同的值。在Scala中,将列表中的值累积为另一种类型的值的操作称为fold。