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 component 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.org/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?
The 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 wantx + y.score.