有没有办法连接js数组中的元素,但让最后一个分隔符不同? [英] Is there a way to join the elements in an js array, but let the last separator be different?
问题描述
我想要的是类似 Array.join(分隔符)
,但它接受第二个参数 Array.join(separator,beforeLastElement)
,所以当我说 [foo,bar,baz] .join(,,或)
我会得到foo,bar或baz
。我想我可以编写一个使用 Array.slice
来分离最后一个元素的函数,但是有一些我可以使用的众所周知的方法吗?
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"
. I guess I could write a function that used Array.slice
to separate out the last element, but is there some well known method that I could use instead?
推荐答案
不,这是特定的,你必须编写一个自定义函数。好消息是,正如你所说,一旦你使用 Array.join
来处理所有的分隔符,最后一个就很容易更新了。
No, this is specific enough that you will have to write a custom function. The good news is, as you said, once you use Array.join
to take care of all the separators, the last one will be easy enough to update.
这篇关于有没有办法连接js数组中的元素,但让最后一个分隔符不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!