简体   繁体   English

JavaScript:缩小和映射

[英]JavaScript: reduce and map

I'm trying to understand why the author of this function would call reduce on an object that is already the result of a call to map. 我试图理解为什么这个函数的作者会在已经是map调用结果的对象上调用reduce。 This is a render function from a backbone app (demo here http://fire-camp.heroku.com/ ). 这是来自主干应用程序的渲染功能(演示位于http://fire-camp.heroku.com/ )。 The variable "messages" represents a collection of the messages the users enter into the messaging system. 变量“ messages”表示用户输入到消息传递系统中的消息的集合。 Why would the author call map and then reduce on the results of map ie 'data.' 作者为什么要调用map,然后减少map的结果,即“数据”。 I don't understand how reduce adds anything new to the data variable. 我不明白reduce如何为数据变量添加任何新内容。 Let me know if you need more information. 如果您需要更多信息,请与我们联系。

render: function() {
    var data = messages.map(function(message) { return message.get('content') + 'n'});
    var result = data.reduce(function(memo,str) { return memo + str }, '');
    $("#chatHistory").text(result);
    return this;
  }

Full source code for the very short app is here but I don't think you'll need it. 简短应用的完整源代码在这里,但我认为您不需要它。 https://github.com/ryandotsmith/fire-camp https://github.com/ryandotsmith/fire-camp

As @Pointy mentioned, the reason the author has used reduce is to concatenate the array into a single string (or reducing it to a string). 正如@Pointy提到的那样,作者使用reduce的原因是将数组连接为单个字符串(或将其简化为字符串)。 As @Pointy also mentions, though, the rationale for using reduce is not very good in this case. 正如@Pointy也提到的那样,在这种情况下使用reduce的原理不是很好。

Given the code on GitHub there are several alternatives that are better. 给定GitHub上的代码,有几种更好的选择。 Considering that the code uses Backbone.js and that the messages variable points to a Backbone.Collection this code would be more clear if it read something along the lines of this: 考虑到代码使用Backbone.js,并且messages变量指向Backbone.Collection如果它按照以下方式读取内容,则该代码将更加清晰:

render: function() {
  var result = messages.pluck('content').join('\n')
  $("#chatHistory").text(result);
  return this;
}

Using reduce for joining an array of strings is overkill and obscures the intention of the code. 使用reduce来连接字符串数组是过大的,并且掩盖了代码的意图。 Using map together with Backbone.Collection just to pluck out a particular attribute from the models inside also somewhat obscures the intention of the code. mapBackbone.Collection一起使用只是为了从模型内部提取特定属性,这在某种程度上也模糊了代码的意图。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM