将数组缩减为单个字符串

新手上路,请多包涵

我想使用 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);

原文由 user3142695 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 335
2 个回答

刚刚收到一连串的答案,这里还有一个!

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

原文由 abigwonderful 发布,翻译遵循 CC BY-SA 3.0 许可协议

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

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

原文由 Shilly 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题