【问题标题】:Why does reduceRight return NaN in Javascript?为什么 reduceRight 在 Javascript 中返回 NaN?
【发布时间】:2011-01-08 06:07:15
【问题描述】:

我正在使用 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 的文档,但显然我无法将 details 数组中的所有 score 值相加。为什么?

【问题讨论】:

    标签: javascript firefox functional-programming reduce


    【解决方案1】:

    试试这个(将转换为数字作为副作用)

    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 } 作为参数。

    【讨论】:

      【解决方案2】:

      reduce 函数应该将两个具有属性“score”的对象组合成一个具有属性“score”的新对象。您将它们组合成一个数字。

      【讨论】:

      • 函数应该将a类型的对象和b类型的对象(其中a是初始值的类型,b是数组的元素类型)组合成a类型的对象。 a 和 b 不必是同一类型。
      • 是的,我意识到这一点。我主要使用 Scala,其中 reduce 操作始终生成与输入列表类型相同的值。在 Scala 中,将列表中的值累积为另一种类型的值的操作称为折叠。
      【解决方案3】:

      函数的第一个参数是累加值。所以第一次调用函数看起来像f(0, {score: 1})。因此,在执行 x.score 时,您实际上是在执行 0.score,这当然是行不通的。换句话说,你想要x + y.score。

      【讨论】:

      • 所以基本上当你将初始值传递给 reduceRight 时,它的行为就像折叠。我没有意识到这一点。
      猜你喜欢
      • 2021-06-18
      • 2020-03-25
      • 1970-01-01
      • 2017-05-10
      • 2020-07-01
      • 2010-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多