【问题标题】:map over properties in array and concat a string in JavaScript es6映射数组中的属性并在 JavaScript es6 中连接字符串
【发布时间】:2016-11-24 13:46:46
【问题描述】:

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

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"

【问题讨论】:

  • 您的浏览器及其版本?
  • 只是names.join(" ")?

标签: javascript arrays string ecmascript-6


【解决方案1】:

我更喜欢使用reduce

ES5 版本

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

ES6 版本

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

【讨论】:

  • 为什么要使用reduce 而不是join?
  • 感谢另一个不错的选择,更多的是一种实用的方法并且效果很好
【解决方案2】:

这是另一个版本,所以你不必映射 --> 加入.. 你可以减少。

const authors = [ { id: 1, name: 'Steven'}, {id: 2, name: 'Nick'}]

console.log(authors.reduce( (p,c) => `${p} ${c.name} is cool `, ""))

【讨论】:

  • map->join 性能最高。检查:jsfiddle.net/abdennour/2btx0c28/4
  • 我相信 reduce 总是会更高效,因为它不必创建中间数组。此外,在您的小提琴中,在 chrome 中,reduce 的性能更高。但我倾向于在 reduce 和 map/join 解决方案之间波动。取决于我的感受。
  • 这会在开头留一个空格。
  • @AbdennourTOUMI 如果要测试性能,请使用专用框架。简单的时间测量毫无意义。
【解决方案3】:

使用Array#Join:

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

DEMO


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

【讨论】:

  • @steveniseki : 我更新了答案,我让代码更优雅(简短)
  • “我让代码更优雅(简短)” (a) => 可以是 a =>
  • 是的@abetteroliver,这很重要,因为它不符合 eslint 规则;查看 aribnb JS 编码约定。
  • 我很困惑。如果您希望您的代码符合要求,那么为什么不更改它呢?
猜你喜欢
  • 1970-01-01
  • 2022-09-26
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 2019-05-11
  • 2018-04-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多