除了最后一个必须用“和”连接的项目外,如何连接字符串类型的数组项目,每个项目都有一个逗号字符?

11 javascript arrays string algorithm

我有一个看起来像这样的字符串数组。

['white t-shirt', 'blue jeans', 'red hat', 'brown glasses'...]
Run Code Online (Sandbox Code Playgroud)

我需要以某种方式用逗号将这些字符串放在以下文本中,但在最后一项而不是逗号之前,我需要设置和。像这样的东西:

'您的卡片包括一件白色 T 恤、蓝色牛仔裤、红色帽子和棕色眼镜, 您可以去结帐页面'

由于我将从后端接收这些数组项,因此我需要以某种方式使上述字符串生成动态化。如果可能的话,如何在没有循环的情况下实现?

Pet*_*ger 11

没有临时保存的引用,但原始strings数组发生了变化......

const strings = ['white t-shirt', 'blue jeans', 'red hat', 'brown glasses'];

console.log(
  [strings.pop(), strings.join(', ')].reverse().join(' and ')
);
console.log('mutated ... strings :', strings);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { min-height: 100%!important; top: 0; }
Run Code Online (Sandbox Code Playgroud)

没有临时保存的引用,这次没有改变原始strings数组......

const strings = ['white t-shirt', 'blue jeans', 'red hat', 'brown glasses'];

console.log(
  [strings.slice(0, strings.length - 1).join(', '), ...strings.slice(-1)].join(' and ')
);
console.log('not mutated ... strings :', strings);
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { min-height: 100%!important; top: 0; }
Run Code Online (Sandbox Code Playgroud)


Yur*_*nko 5

IntlAPI有一部分称为Intl.ListFormat. 如果您想根据区域设置规则进行正确的列表格式设置,我建议您使用它而不是手动格式设置。

例如,在提供的情况下,“and”之前应该有一个逗号。

const strings = ['white t-shirt', 'blue jeans', 'red hat', 'brown glasses'];

const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log(formatter.format(strings));

const short = ['white t-shirt', 'blue jeans'];

console.log(formatter.format(short));
Run Code Online (Sandbox Code Playgroud)