有没有办法将js数组中的元素连接起来,但让最后一个分隔符不同?

新手上路,请多包涵

What I want is something like Array.join(separator) , but which takes a second argument Array.join(separator, beforeLastElement) , so when I say [foo, bar, baz].join(", ", " or") I would get "foo, bar or baz" .我想我可以编写一个使用 Array.slice 的函数来分离出最后一个元素,但是有一些众所周知的方法可以代替吗?

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

阅读 253
2 个回答

2021 年的更新答案!

如果目标是在倒数第二个和最后一个元素之间使用不同的分隔符,例如“and”或“or”,您可以使用 Intl.ListFormat

它确实做到了这一点,并且您可以免费获得 i18n。

它在除 IE11 之外的所有主要浏览器中都受支持。

例子:

 const vehicles = ['Motorcycle', 'Bus', 'Car'];

const formatter = new Intl.ListFormat('en', { style: 'long', type: 'conjunction' });
console.log(formatter.format(vehicles));
// expected output: "Motorcycle, Bus, and Car"

const formatter2 = new Intl.ListFormat('de', { style: 'short', type: 'disjunction' });
console.log(formatter2.format(vehicles));
// expected output: "Motorcycle, Bus oder Car"

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

没有预定义函数,因为它非常简单。

 var a = ['a', 'b', 'c'];
var str = a.slice(0, -1).join(',')+' or '+a.slice(-1);

这种功能的主要用例也存在规范问题,即自然语言格式化。例如,如果我们要使用牛津逗号逻辑,我们将得到与您要查找的结果不同的结果:

 // make a list in the Oxford comma style (eg "a, b, c, and d")
// Examples with conjunction "and":
// ["a"] -> "a"
// ["a", "b"] -> "a and b"
// ["a", "b", "c"] -> "a, b, and c"
exports.oxford = function(arr, conjunction, ifempty){
    let l = arr.length;
    if (!l) return ifempty;
    if (l<2) return arr[0];
    if (l<3) return arr.join(` ${conjunction} `);
    arr = arr.slice();
    arr[l-1] = `${conjunction} ${arr[l-1]}`;
    return arr.join(", ");
}

所以让这个问题出现在用户空间似乎更好。

原文由 Denys Séguret 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题