Javascript 将数组缩减为单个字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38270089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:15:52  来源:igfitidea点击:

Reduce array to a single string

javascriptunderscore.js

提问by user3142695

I would like to use the reducefunction instead of doing this:

我想使用该reduce功能而不是这样做:

var result = '';
authors.forEach(
    function(author) {
        result += author.name + ', ';
    }
);
console.log(result);

So in the array authorsthere are several names. Now I want to build a string with this names, separated by comma (except the last one).

所以在数组中authors有几个名字。现在我想用这个名字建立一个字符串,用逗号分隔(最后一个除外)。

var result = authors.reduce(function (author, index) {
    return author + ' ';
}, '');
console.log(result);

回答by abigwonderful

A flurry of answers just came in and here is one more!

一连串的答案刚刚出现,这里还有一个!

The first option is using the native js join method which eliminates the need for reduce. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

第一个选项是使用原生 js join 方法,它消除了对 reduce 的需要。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join

var authors = ['some author', 'another author', 'last author'];
var authorString = authors.join(",");
console.log(authorString);

IMPORTANT- if you're array contains objects, then you might want to map it before joining:

重要- 如果您的数组包含对象,那么您可能需要在加入之前映射它:

var authors = [{name: 'some author'},{name: 'another author'},{name: 'last author'}]
var authorString = authors.map(function(author){
    return author.name;
}).join(",");
console.log(authorString);

or, if you're really fired up about using reduce, just make sure you use the previous value, current value and index when passing in the callback. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

或者,如果您真的对使用 reduce 感到兴奋,只需确保在传入回调时使用先前的值、当前值和索引。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

var authorString = authors.reduce(function(prevVal,currVal,idx){
    return idx == 0 ? currVal : prevVal + ', ' + currVal;
}, '')
console.log(authorString);

IMPORTANT- again if your array contains objects then you will want to make sure you are using the 'name property':

重要- 如果您的数组包含对象,那么您需要确保使用的是“名称属性”:

var authors = [{name: 'some author'},{name: 'another author'},{name: 'last author'}];
var authorString = authors.reduce(function(prevVal,currVal,idx){
    return idx == 0 ? currVal.name : prevVal + ', ' + currVal.name;
}, '')
console.log(authorString);

回答by Shilly

Right, so it's an object. Let's map the names first then:

对,所以它是一个对象。让我们先映射名称然后:

var result = authors.map(function( author ) {
    return author.name;
}).join(', ');

回答by epascarello

You are reinventing join()

你正在重新发明 join()

var authors = ["a","b","c"];
var str = authors.join(", ");
console.log(str);

if you want to use reduce add an if check

如果你想使用 reduce 添加一个 if 检查

var authors = ["a","b","c"];

var result = authors.reduce(function (author, val, index) {
    var comma = author.length ? ", " : "";
    return author + comma + val;
}, '');
console.log(result);



Since I missed the mapping part to make people happy...

由于我错过了让人们开心的映射部分......

var authors = [{
  name: "a"
}, {
  name: "b"
}, {
  name: "c"
}];

var res = authors.map( function(val) { return val.name; }).join(", ");
console.log(res);

OR

或者

var authors = [{
  name: "a"
}, {
  name: "b"
}, {
  name: "c"
}];
var result = authors.reduce(function(author, val, index) {
  var comma = author.length ? ", " : "";
  return author + comma + val.name;
}, '');
console.log(result);

回答by Ronjark

I came across this also. Most of these answers dont take into account that you want the authorsname, meaning you have an array of objects.

我也遇到了这个。这些答案中的大多数都没有考虑到您想要作者姓名,这意味着您有一组对象。

A one line solution:

一行解决方案:

authors.reduce((prev, curr) => [...prev, curr.name], []).join(', ');

回答by elreeda

Try this:

尝试这个:

var authors = ["Mikel", "Brad", "Jessy", "Pof", "MArting"]
var result = authors.reduce( (prev, curr) => prev +', '+ curr )

console.log(result)