【问题标题】:.Reduce without an accumulator.减少没有累加器
【发布时间】:2015-06-04 04:18:44
【问题描述】:

在这方面遇到了很多麻烦,以至于我迫切希望朝着正确的方向前进。

通过编写reduce 函数尝试完成一个常见的Underbar(基本上是Underscore)练习。它必须满足四个测试:

  1. 应该能对数组求和
  2. 如果没有给出第一个元素,则应将其用作累加器
  3. 当给定累加器时,应该涉及第一个元素上的迭代器
  4. 将第一个元素用作累加器时,不应在第一个元素上调用迭代器

这向我表明有两种基本情况:

  1. 给出了一个累加器,使累加器 != 未定义,此时您可以使用 .each 来满足测试 1 和 3,因为您将遍历所有值,从 (accumulator, collection[0]) 开始,然后 (集合[0]、集合[1])等。或者这就是我的想法;我可能会走得很远。

    if (accumulator != undefined) {
      _.each(collection, function(value) {
        accumulator = iterator(accumulator, value);
      });
    }
    return accumulator; 
    
  2. 测试 2 和 4 仍然失败,因为没有给出累加器,那时我迷路了。我不认为 .each 可以使用。基本上我必须告诉这个从 collection[0] 开始并遍历其余部分,但我完全迷失了。我对编码还是很陌生,其中很多内容还没有完全融入。

我们非常感谢您提供的任何帮助。如果我对这些功能如何工作的想法有误,也请随时纠正。我只是在寻求帮助。

【问题讨论】:

  • 正常的for 循环怎么样?
  • 在没有提供累加器时使用 _.first 和 _.rest

标签: javascript iterator underscore.js reduce


【解决方案1】:

下面的代码应该完成这项工作。

Array.prototype.reduce = function(callback, accumulator){
	var needsAccum = arguments.length <2;
	if (this.length === 0){
		return this;
	}
	this.forEach(function(item){
		if (needsAccum){
			accumulator = item;
			needsAccum = false;
		}
		else{
			accumulator = callback(accumulator, item)
		}
	})
	return accumulator;
}

【讨论】:

    【解决方案2】:

    所以总结部分问题:

    “我如何使用 _.each 进行迭代,有时我不得不跳过第一次迭代” - “不会 _.each 在每个索引处迭代吗?”

    对我来说,我发现解决方案是在我的 _.each 中添加一个 if/else 语句

    _.each(collection, function(value, index) {
      if (accumulator === undefined){
        accumulator = item;
      } else {
        accumulator = iterator(accumulator, value);
      }
    }
    

    基本上,将 if 语句放在 _.each 中,而不是放在它之前。 在第一次迭代中,如果没有累加器,则循环进入“IF”,并跳过“ELSE”

    【讨论】:

      猜你喜欢
      • 2018-01-23
      • 2020-12-15
      • 2022-01-08
      • 2014-12-16
      • 2018-08-05
      • 2015-05-18
      • 2018-10-18
      • 2018-07-29
      • 2020-08-11
      相关资源
      最近更新 更多