【问题标题】:Why Array.prototype.reduce() is not taking an empty array as accumulator?为什么 Array.prototype.reduce() 不将空数组作为累加器?
【发布时间】:2015-12-15 00:59:48
【问题描述】:

我正在尝试将数组中大于 10 的所有元素过滤到一个新数组中。我故意不使用Array.prototype.filter(),因为我想学习reduce() 方法。这是我正在玩的代码

var collection = [3, 5, 11, 23, 1];

// fileter all the elements bigger than 10 to a new array

var output = collection.reduce(function(filteredArr, collectionElemet) {
  if (collectionElemet > 10) {
    return filteredArr.push(collectionElemet);
  }
}, []);

我期待filteredArr 在第一次回调执行时会被初始化为一个空数组,就像here 提供的许多示例一样。但是当我运行这段代码时,我得到了错误 Cannot read property 'push' of undefined,我在哪里搞砸了?谢谢!

【问题讨论】:

  • 如果条件为真 - 你返回一个数字,如果不是真 - 你返回一个undefined。如果您只是想过滤 - 使用 Array.prototype.filter,您当前的代码是丑陋且具有误导性的。
  • @zerkms:这对生产代码是公平的,而不是教育/实验。 OP 明确表示他知道filter,但正试图了解reduce

标签: javascript arrays reduce


【解决方案1】:

当您尝试执行return filteredArr.push(collectionElement) 时,本质上您是在推送操作后返回filteredArr 的长度。 push() 方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。 参考:Array.prototype.push().

您需要从匿名函数中返回filteredArr,以便将其用作下次调用的previousValue

var collection = [3, 5, 11, 23, 1];

// filter all the elements bigger than 10 to a new array

var output = collection.reduce(function(filteredArr, collectionElement) {
  if (collectionElement > 10) {
    filteredArr.push(collectionElement);
  }
  return filteredArr;
}, []);

【讨论】:

    【解决方案2】:

    Array.prototype.push 将返回新数组的长度。您需要退回蓄能器。一个简洁的方法是使用Array.prototype.concat,因为该方法实际上会返回数组:

    var collection = [3, 5, 11, 23, 1];
    
    var output = collection.reduce(function(filteredArr, collectionElemet) {
      if (collectionElemet > 10) {
        return filteredArr.concat(collectionElemet);
      }
    }, []);
    

    您必须返回累加器,以便下一次迭代可以使用累加器的值。

    【讨论】:

    • 不是我的反对意见,但 concat 每次都返回一个新数组,效率低下。 push 是将新元素附加到现有数组的明显选择。
    • 并不总是与效率有关,这是有效的答案,因为说明了两件事,如何在一行中提出解决方案,并且@segmentationfaulter 必须返回filteredArr。他的困惑可能是认为filteredArr.push 会返回filteredArr。
    猜你喜欢
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    • 2016-08-23
    • 2021-03-14
    • 2016-02-14
    • 2015-07-26
    • 2013-10-14
    • 1970-01-01
    相关资源
    最近更新 更多