将数组简化为单个字符串

我想使用 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);
127236 次浏览

您正在重新发明 join ()

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

如果你想使用 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);


因为我为了让大家开心而错过了地图部分。

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


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

或者

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

试试这个:

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


console.log(result)

好的,这是一个对象,我们先把名字映射出来:

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

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

第一个选项是使用本机 js 连接方法,它消除了对 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 感到非常兴奋,那么在传递回调时,只需确保使用以前的值、当前值和 index 即可。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);

我还发现了这个。 这些答案中的大多数都没有考虑到您想要的 author<是的trong>是的名称,这意味着您有一个对象数组。

一个简单的解决办法:

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