用逗号和"和"加入一个数组

Mer*_*erc 21 javascript arrays string

我想将数组['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? '' : ', '), '' )
Run Code Online (Sandbox Code Playgroud)

它是基于在添加逗号结束 -与第二最后一个(除外a.length - 2),并用的方式,以避免最后一个逗号(a.length - 2).

SURELY必须有一个更好,更整洁,更智能的方式来做到这一点?

在搜索引擎上搜索是一个很难的主题,因为它包含"和"这个词......

Cer*_*nce 26

一个选项是pop最后一个项目,然后是join所有其余的逗号,并连接and加上最后一项:

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

如果您不能改变输入数组,请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']));
Run Code Online (Sandbox Code Playgroud)

  • 非常好,以为缺少牛津逗号就是在杀我. (7认同)

小智 12

我喜欢Mark Meyer的方法(并且如果我有代表则会提升),因为它不会改变输入.这是我的旋转:

function makeCommaSeparatedString(arr, useOxfordComma) {
    const listStart = arr.slice(0, -1).join(', ');
    const listEnd = arr.slice(-1);
    const conjunction = arr.length <= 1 ? '' :
        useOxfordComma && arr.length > 2 ? ', and ' : ' and ';

    return [listStart, listEnd].join(conjunction);
}

console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four']));
// one, two, three and four
console.log(makeCommaSeparatedString(['one', 'two', 'three', 'four'], true));
// one, two, three, and four
console.log(makeCommaSeparatedString(['one', 'two'], true));
// one and two
console.log(makeCommaSeparatedString(['one']));
// one
console.log(makeCommaSeparatedString([]));
// 
Run Code Online (Sandbox Code Playgroud)


Yos*_*ero 8

当大于1 时,可以使用Array.prototype.slice()array.length并排除其余的情况:

const result = a => a.length > 1 
  ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` 
  : {0: '', 1: a[0]}[a.length];
Run Code Online (Sandbox Code Playgroud)

代码示例:

const input1 = ['one', 'two', 'three', 'four'];
const input2 = ['A Tale of Two Cities', 'Harry Potter and the smth', 'One Fish, Two Fish, Red Fish, Blue Fish'];
const input3 = ['one', 'two'];
const input4 = ['one'];
const input5 = [];

const result = a => a.length > 1 
  ? `${a.slice(0, -1).join(', ')} and ${a.slice(-1)}` 
  : {0: '', 1: a[0]}[a.length];

console.log(result(input1));
console.log(result(input2));
console.log(result(input3));
console.log(result(input4));
console.log(result(input5));
Run Code Online (Sandbox Code Playgroud)


Bap*_*ier 8

从V8 v7.2和Chrome 72开始,您可以使用甜蜜的Intl.ListFormatAPI.它还会在需要时对您的列表进行本地化处理,如果您需要它可能会有很大的帮助.

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'
Run Code Online (Sandbox Code Playgroud)

您甚至可以指定选项以使其中断并使用"或"代替"和",或者格式化单位,例如"3英尺7英寸".

参考
Intl.ListFormat API - Google Developers
V8发行版v7.2


小智 6

使用数组#reduce:

['one', 'two', 'three', 'four'].reduce( (a, b, i, array) => a + (i < array.length - 1 ? ', ' : ' and ') + b)

  • @Zack你的三元数缺少一个冒号。应该是 `heresHowToHandleOxfords.reduce( (a, b, i, array) =&gt; a + ( i &lt; array.length - 1 ? ', ' : (array.length &gt; 2 ? ', and ' : ' and ') ) + b)`。感谢您的解决方案! (3认同)
  • 轻松获胜。事实上,这个答案今天到目前为止已经下降了,这说明了这个社区对新箭头函数的惊人抵制,作为一个最近才涉足 js 的人,我对此感到惊讶。我们想要一个表达式完全按照要求执行操作,还是需要三行代码?我们可以调用一个五行函数怎么样?哎呀人们! (2认同)