我想使用 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);
最佳答案
刚刚出现了一系列答案,还有一个!
第一个选项是使用原生 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);
重要 - 如果您的数组包含对象,那么您需要确保使用“名称属性”:
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);
关于javascript - 将数组缩减为单个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38270089/