将数组减少为单个字符串

时间:2016-07-08 15:13:32

标签: javascript underscore.js

我想使用reduce函数而不是这样做:

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

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

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

5 个答案:

答案 0 :(得分:37)

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

第一个选项是使用本机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);

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

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

或者,如果您真的对使用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);

重要 - 如果您的数组包含对象,那么您需要确保使用' name属性':

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);

答案 1 :(得分:13)

是的,所以这是一个对象。让我们首先映射名称:

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

答案 2 :(得分:2)

你正在重塑join()



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




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



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

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




因为我错过了映射部分让人们开心......



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);




答案 3 :(得分:0)

我也遇到了这个。 大多数答案都没有考虑到你想要作者 s 这个名字,这意味着你有一个对象数组。

一线解决方案:

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

答案 4 :(得分:-1)

试试这个:

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

console.log(result)