代码之家  ›  专栏  ›  技术社区  ›  Emre Sevinç

为什么reducceright在javascript中返回NaN?

  •  0
  • Emre Sevinç  · 技术社区  · 15 年前

    我使用的是火狐3.5.7,在Firebug中,我尝试测试array.reducerlight函数,它适用于 简单数组 但是当我尝试这样的事情时,我得到了 . 为什么?

    >>> 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 但很明显我不能把所有的 分数 我的价值观 细节 数组。为什么?

    3 回复  |  直到 15 年前
        1
  •  6
  •   sepp2k    15 年前

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

        2
  •  4
  •   Hogan    15 年前

    尝试此操作(将转换为数字作为副作用)

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

        3
  •  0
  •   Willis Blackburn    15 年前

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