我想要的是类似 Array.join(separator)
的东西,但它需要第二个参数 Array.join(separator, beforeLastElement)
,所以当我说 [foo, bar, baz].join(", ", "or")
我会得到 "foo, bar or baz"
。我想我可以编写一个使用 Array.slice
来分隔最后一个元素的函数,但是是否有一些我可以改用的众所周知的方法?
最佳答案
没有预定义函数,因为它非常简单。
var a = ['a', 'b', 'c'];
var str = a.slice(0, -1).join(',')+' or '+a.slice(-1);
这种功能的主要用例也存在规范问题,即自然语言格式化。例如,如果我们使用 Oxford 逗号逻辑,我们将得到与您正在寻找的结果不同的结果:
// 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(", ");
}
所以让这个问题出现在用户空间似乎更好。
关于javascript - 有没有办法将js数组中的元素连接起来,但让最后一个分隔符不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15069587/