[英]Why does [NaN].includes(NaN) return true in JavaScript?
[英]Why does reduceRight return NaN in Javascript?
我正在使用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/zh-CN/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight中阅读了文档,但显然我无法使它汇总我的详细信息数组中的所有得分值。 为什么?
给该函数的第一个参数是累加值。 因此,对该函数的首次调用将类似于f(0, {score: 1})
。 因此,在执行x.score时,实际上是在执行0.score,这当然是行不通的。 换句话说,您想要x + y.score
。
试试这个(副作用会转换为数字)
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 }
作为参数。
reduce函数应将两个具有“分数”属性的对象组合为一个具有“分数”属性的新对象。 您正在将它们组合成一个数字。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.