【问题标题】:return elements separated by comm from an array of objects [duplicate]从对象数组中返回由 comm 分隔的元素 [重复]
【发布时间】:2020-09-25 08:26:58
【问题描述】:

你好,我有一个这样的数组

const persons = [{name: 'John'}, {name: 'Rick'}, {name: 'Amy'}]

我想用逗号隔开,并在最后一个元素前加上“and”

John, Rick and Amy

我可以的

persons.map(person => <span>{person.name}, </span>)

但这会产生

John, Rick, Amy, 

有没有一种更有效(花哨)的方法来代替迭代数组并在除最后一个元素之外的所有元素之前添加“,”?

【问题讨论】:

    标签: javascript reactjs ecmascript-6


    【解决方案1】:

    让我们尝试简单检查元素索引后的条件:

    const persons = [{name: 'John'}, {name: 'Rick'}, {name: 'Amy'}]
    const formmatted = persons.map((p,i) => (p.name + (i === persons.length - 2 ? ' and ' : (i !== persons.length - 1 ? ', ' : '')))).join("");
    console.log(formmatted);

    【讨论】:

      猜你喜欢
      • 2023-01-26
      • 2017-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      相关资源
      最近更新 更多