映射数组中的属性,并在JavaScriptes6中连接一个字符串

map over properties in array and concat a string in JavaScript es6

本文关键字:一个 字符串 连接 JavaScriptes6 数组 属性 并在 映射      更新时间:2023-09-26

我有以下对象数组,例如一些作者,我想映射它们并返回一个与一些格式连接的字符串。出于某种原因,我对这个相当简单的事情有意见。

const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]
let names = authors.map( (a, i) => {
  return `${a.name} is cool`
})
console.log(names)
// ["Steven is cool","Nick is cool"]
// but I really want the string "Steven is cool Nick is cool"

我如何将其映射并格式化为字符串?

例如"Steven is cool Nick is cool"

使用Array#Join:

authors.map((a) => `${a.name} is cool`).join(' ');

演示


注:join与ES6无关,它是旧的。

i对于喜欢使用减少的人

ES5版本

autors.reduce(function (str, person) { 
  return (str+' '+person.name+ ' is cool');
}, ''); 

ES6版本

autors.reduce((str, person) => `${str} ${person.name} is cool`, '');

这里有另一个版本,所以您不必映射-->join。。你可以减少。

const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]
console.log(authors.reduce( (p,c) => `${p} ${c.name} is cool `, ""))