为什么reduceRight在Javascript中返回NaN? [英] Why does reduceRight return NaN in Javascript?

查看:414
本文介绍了为什么reduceRight在Javascript中返回NaN?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Firefox 3.5.7和Firebug内部我试图测试array.reduceRight函数,它适用于简单数组,但是当我尝试这样的事情时,我得到一个 NaN的即可。为什么?

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

我也尝试过map,至少我可以看到每个元素的.score组件:

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]

我阅读 https://developer.mozilla.org/zh/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight 但显然我不能得到它的工作总和在我的详细信息数组中添加所有分数值。为什么?

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?

推荐答案

给函数的第一个参数是累计值。所以对函数的第一个调用看起来像 f(0,{score:1})。所以当做x.score时,你实际上正在做0.score,当然不行。换句话说,你需要 x + y.score

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 want x + y.score.

这篇关于为什么reduceRight在Javascript中返回NaN?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆