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

relj7zay  于 2023-05-27  发布在  Java
关注(0)|答案(7)|浏览(155)

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

3htmauhk1#

一系列的答案刚刚进来,这里是一个更多!
第一个选择是使用原生的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);

重要-如果你的数组包含对象,那么你可能需要在加入之前Map它:

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 property':

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

iyfamqjs2#

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

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

mefy6pfw3#

您正在重新创建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);

因为我错过了让人们高兴的Map部分...

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

dfddblmv4#

我也遇到了这个。这些答案中的大多数都没有考虑到你想要作者的名字,这意味着你有一个对象数组。
一行解决方案:

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

91zkwejq5#

试试这个:

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

console.log(result)
oiopk7p5

oiopk7p56#

这里是一个“Python Like”方法,使用数组或Object在一行中构建字符串。

// From an Array
['Hey', 'Hi', 'Hello!'].reduce((result, item, index) => (index !==0 ? `${result}, `: '')+`${item}`, '')

// From an Object
Object.entries({one: 1, two: 2, three: 3}).reduce((result, [key, value], index) => (index !==0 ? `${result}, `: '')+`${key} -> ${value}`, '')

希望这能帮上忙。干杯

sxpgvts3

sxpgvts37#

我将添加我的2美分,这里有两个选项,通过map或使用三元运算符:

const authors = [{name: 'John'}, {name: 'Jack'}, {name: 'Charles'}];

// Map
const reducedMap = authors.map(a => a.name).reduce((result, name) => `${result},${name}`);

// Ternary operator and initial value
const reducedTernary = authors.reduce((result, author) => `${result}${result ? ',' : ''}${author.name}` , '');

// Result :
// John,Jack,Charles

相关问题