Javascript:很好的人类可读的列表连接 [英] Javascript: nice human readable join of list
问题描述
有一个标签列表(数组) ['tag1','tag2','tag3']
我想生成一个好的标题,如:内容标记为tag1,tag2和tag3
。
Having a list (array) of tags ['tag1', 'tag2', 'tag3']
I want to generate a nice title like: Content tagged tag1, tag2 and tag3
.
目前我有:
"Content tagged " + tags_titles.join(" and ");
结果:
内容标记为tag1,tag2和tag3
我知道这是一个简单的问题,但我很好奇是否有一个很好的解决方案。
I know it's a simple question, but I am curious if there is a nice solution for this case.
推荐答案
你可以得到最后两个元素并用'和'
加入它们并把它作为最后一个元素返回数组,然后用','
连接所有元素以获得一个好的字符串。
You could get the two last elements and join them with ' and '
and put it as last element back into the array and later join all elements with ', '
for getting a nice string.
方法
-
Array#concat
,连接两个数组并返回一个新数组
Array#concat
, joins two arrays and returns a new array
Array#splice
,用于获取数组的最后两个元素
Array#splice
, for getting the last two elemensts of the array
数组#join
,加入带有给定间隔符的数组。
Array#join
, joins an array with the given spacer.
此提案适用于任何长度的数组,即使只有一个或两个元素。
This proposal works for any length of an array, even with one or two elements.
function nice(array) {
return array.concat(array.splice(-2, 2).join(' and ')).join(', ');
}
console.log("Content tagged " + nice(['tag1']));
console.log("Content tagged " + nice(['tag1', 'tag2']));
console.log("Content tagged " + nice(['tag1', 'tag2', 'tag3']));
这篇关于Javascript:很好的人类可读的列表连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!