javascript – 将数组减少为单个字符串

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

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

所以在阵列作者中有几个名字.现在我想用这个名字构建一个字符串,用逗号分隔(除了最后一个).

var result = authors.reduce(function (author, index) {
    return author + ' ';
}, '');
console.log(result);
一连串的答案刚刚进来,这里还有一个!

第一个选项是使用本机js连接方法,这消除了减少的需要. 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);
相关文章
相关标签/搜索