admin管理员组文章数量:1405134
I'm using Firefox 3.5.7 and within Firebug I'm trying to test the array.reduceRight function, it works for simple arrays but when I try something like that I get a NaN. Why?
>>> 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
I also tried map and at least I can see the .score ponent of each element:
>>> details.map(function(x) {console.log (x.score);})
1
2
3
[undefined, undefined, undefined]
I read the documentation at .5_Reference/Objects/Array/reduceRight but apparently I can't get it work to sum up all the score values in my details array. Why?
I'm using Firefox 3.5.7 and within Firebug I'm trying to test the array.reduceRight function, it works for simple arrays but when I try something like that I get a NaN. Why?
>>> 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
I also tried map and at least I can see the .score ponent of each element:
>>> details.map(function(x) {console.log (x.score);})
1
2
3
[undefined, undefined, undefined]
I read the documentation at https://developer.mozilla/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight but apparently I can't get it work to sum up all the score values in my details array. Why?
Share Improve this question edited Jan 22, 2010 at 15:37 Emre Sevinç asked Jan 22, 2010 at 15:07 Emre SevinçEmre Sevinç 8,53114 gold badges69 silver badges108 bronze badges3 Answers
Reset to default 7The first argument given to the function is the accumulated value. So the first call to the function will look like f(0, {score: 1})
. So when doing x.score, you're actually doing 0.score which doesn't work of course. In other words you want x + y.score
.
try this (will convert to numbers as side effect)
details.reduceRight(function(previousValue, currentValue, index, array) {
return previousValue + currentValue.score;
}, 0)
or this
details.reduceRight(function(previousValue, currentValue, index, array) {
var ret = { 'score' : previousValue.score + currentValue.score} ;
return ret;
}, { 'score' : 0 })
Thanks to @sepp2k for pointing out how { 'score' : 0 }
was needed as a parameter.
The reduce function should bine two objects with a property "score" into a new object with a property "score." You're bining them into a number.
本文标签: firefoxWhy does reduceRight return NaN in JavascriptStack Overflow
版权声明:本文标题:firefox - Why does reduceRight return NaN in Javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744885890a2630481.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论