简体   繁体   中英

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. This is a render function from a backbone app (demo here http://fire-camp.heroku.com/ ). The variable "messages" represents a collection of the messages the users enter into the messaging system. Why would the author call map and then reduce on the results of map ie 'data.' I don't understand how reduce adds anything new to the data variable. 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

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). As @Pointy also mentions, though, the rationale for using reduce is not very good in this case.

Given the code on GitHub there are several alternatives that are better. 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:

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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