通过逗号和“and”加入数组

新手上路,请多包涵

我想将数组 ['one', 'two', 'three', 'four'] 转换成 one, two, three and four

请注意,第一个项目有一个逗号,但倒数第二个和最后一个之间有单词 and

我想出的最佳解决方案:

 a.reduce( (res, v, i) => i === a.length - 2 ? res + v + ' and ' : res + v + ( i == a.length -1? '' : ', '), '' )

它基于在 末尾 添加逗号——倒数第二个逗号 ( a.length - 2 ) 除外,并且有一种方法可以避免最后一个逗号 ( a.length - 2 )。

肯定有更好、更整洁、更智能的方法来做到这一点吗?

这是一个很难在搜索引擎上搜索的主题,因为它包含单词“和”……

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

阅读 349
2 个回答

一种选择是 pop 最后一项,然后 join 其余所有用逗号连接,并与 and 加上最后一项- 连接:

 const input = ['one', 'two', 'three', 'four'];
const last = input.pop();
const result = input.join(', ') + ' and ' + last;
console.log(result);

如果您不能改变输入数组,请使用 slice 代替,如果输入数组中可能只有一项,请先检查数组的长度:

 function makeString(arr) {
  if (arr.length === 1) return arr[0];
  const firsts = arr.slice(0, arr.length - 1);
  const last = arr[arr.length - 1];
  return firsts.join(', ') + ' and ' + last;
}

console.log(makeString(['one', 'two', 'three', 'four']));
console.log(makeString(['one']));

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

从 V8 v7.2 和 Chrome 72 开始,您可以使用 sweet Intl.ListFormat API。它还会在请求时负责本地化您的列表,如果您需要,这可能会有很大帮助。

 const lf = new Intl.ListFormat('en');

console.log(lf.format(['Frank']));
// → 'Frank'

console.log(lf.format(['Frank', 'Christine']));
// → 'Frank and Christine'

console.log(lf.format(['Frank', 'Christine', 'Flora']));
// → 'Frank, Christine, and Flora'

console.log(lf.format(['Frank', 'Christine', 'Flora', 'Harrison']));
// → 'Frank, Christine, Flora, and Harrison'

// You can use it with other locales
const frlf = new Intl.ListFormat('fr');

console.log(frlf.format(['Frank', 'Christine', 'Flora', 'Harrison']));
// → 'Frank, Christine, Flora et Harrison'

您甚至可以指定选项使其中断并使用“或”而不是“和”,或格式化“3 英尺,7 英寸”等单位。

在撰写本文时,它还没有 得到广泛支持,因此您可能不想在任何地方都使用它。

参考

Intl.ListFormat API - Google Developers

V8 发布 v7.2

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

推荐问题