为什么在 JavaScript 中,reduceRight 返回 NaN?
我正在使用 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/en/Core_JavaScript_1.5_Reference/Objects/Array/reduceRight 但显然我无法让它工作来总结所有分数我的详细信息数组中的值。为什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
赋予该函数的第一个参数是累积值。因此,对该函数的第一次调用将类似于
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 wantx + y.score
.尝试这个(将转换为数字作为副作用)
或这个
感谢@sepp2k指出如何需要
{ 'score' : 0 }
作为参数。try this (will convert to numbers as side effect)
or this
Thanks to @sepp2k for pointing out how
{ 'score' : 0 }
was needed as a parameter.reduce 函数应该将两个具有属性“score”的对象合并为一个具有属性“score”的新对象。您将它们组合成一个数字。
The reduce function should combine two objects with a property "score" into a new object with a property "score." You're combining them into a number.