javascript 有没有办法在js数组中加入元素,但让最后一个分隔符不同?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15069587/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Is there a way to join the elements in an js array, but let the last separator be different?
提问by Eivind Eidheim Elseth
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(separator)
,但这需要第二个参数Array.join(separator, beforeLastElement)
,所以当我说[foo, bar, baz].join(", ", " or")
我会得到"foo, bar or baz"
. 我想我可以编写一个用于Array.slice
分离最后一个元素的函数,但是有没有一些众所周知的方法可以代替?
采纳答案by Justin Ethier
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.
不,这足够具体,您必须编写自定义函数。好消息是,正如您所说,一旦您使用Array.join
了所有分隔符,最后一个将很容易更新。
回答by Denys Séguret
There's no predefined function, because it's quite simple.
没有预定义的函数,因为它非常简单。
var a = ['a', 'b', 'c'];
var str = a.slice(0, -1).join(',')+' or '+a.slice(-1);
There's also a specification problem for the main use case of such a function which is natural language formatting. For example if we were to use the Oxford comma logic we would have a different result than what you're looking for:
这种函数的主要用例也存在规范问题,即自然语言格式。例如,如果我们要使用牛津逗号逻辑,我们将得到与您要查找的结果不同的结果:
// 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(", ");
}
So it seems better to let this problem in userland.
所以把这个问题放在用户空间似乎更好。
回答by Joseph
May I suggest:
我可以建议:
['tom', 'dick', 'harry'].join(', ').replace(/, ([^,]*)$/, ' and ')
> "tom, dick and harry"
回答by CBarr
Building off of @dystroy's answer:
基于@dystroy 的回答:
function formatArray(arr){
var outStr = "";
if (arr.length === 1) {
outStr = arr[0];
} else if (arr.length === 2) {
//joins all with "and" but no commas
//example: "bob and sam"
outStr = arr.join(' and ');
} else if (arr.length > 2) {
//joins all with commas, but last one gets ", and" (oxford comma!)
//example: "bob, joe, and sam"
outStr = arr.slice(0, -1).join(', ') + ', and ' + arr.slice(-1);
}
return outStr;
}
Example usages:
示例用法:
formatArray([]); //""
formatArray(["a"]); //"a"
formatArray(["a","b"]); //"a and b"
formatArray(["a","b","c"]); //"a, b, and c"
formatArray(["a","b","c","d"]); //"a, b, c, and d"
回答by Charlie Wynn
Array.prototype.join2 = function(all, last) {
var arr = this.slice(); //make a copy so we don't mess with the original
var lastItem = arr.splice(-1); //strip out the last element
arr = arr.length ? [arr.join(all)] : []; //make an array with the non-last elements joined with our 'all' string, or make an empty array
arr.push(lastItem); //add last item back so we should have ["some string with first stuff split by 'all'", last item]; or we'll just have [lastItem] if there was only one item, or we'll have [] if there was nothing in the original array
return arr.join(last); //now we join the array with 'last'
}
> [1,2,3,4].join2(', ', ' and ');
>> "1, 2, 3 and 4"
回答by Pawe?
there is a package join-array
有一个包join-array
const join = require('join-array');
const names = ['Rachel','Taylor','Julia','Robert','Jasmine','Lily','Madison'];
const config = {
array: names,
separator: ', ',
last: ' and ',
max: 4,
maxMessage:(missed)=>`(${missed} more...)`
};
const list = join(config); //Rachel, Taylor, Julia, (3 more...) and Madison
回答by Vignesh Raja
Though its a late answer, adding some approaches.
虽然它是一个迟到的答案,但添加了一些方法。
Method 1: Using Array.splice() add the last delimiter
before last element and join and remove the last two ,
.
方法 1:使用 Array.splice() 添加last delimiter
前最后一个元素并连接和删除最后两个,
。
function join(arr,last)
{
if(!Array.isArray(arr)) throw "Passed value is not of array type.";
last = last || ' and '; //set 'and' as default
(arr.length>1 && arr.splice(-1,0,last));
arr = arr.join().split("");
arr[arr.lastIndexOf(",")]="";
arr[arr.lastIndexOf(",")]="";
return arr.join("");
}
console.log( join([1]) ); //single valued array
console.log( join([1,2]) ); //double valued array
console.log( join([1,2,3]) ); //more than 2 values array,
console.log( join([1,2,3],' or ') ); //with custom last delimiter
console.log( join("name") ); //Non-array type
Method 2: Using Array.reduce() to construct the string by traversing each element.
方法二:使用Array.reduce()遍历每个元素来构造字符串。
function join(arr,last)
{
if(!Array.isArray(arr)) throw "Passed value is not of array type.";
last=last||' and ';
return arr.reduce(function(acc,value,index){
if(arr.length<2) return arr.join();
return acc + (index>=arr.length-2 ? index>arr.length-2 ? value : value+last : value+",");
},"");
}
console.log( join([1]) ); //single valued array
console.log( join([1,2]) ); //double valued array
console.log( join([1,2,3]) ); //more than 2 values array,
console.log( join([1,2,3,4],' or ') ); //with custom last delimiter
console.log( join("name") ); //Non-array type
回答by Yair Levy
compact version :)
紧凑版:)
function customJoin(arr,s1,s2){
return(arr.slice(0,-1).join(s1).concat(arr.length > 1 ? s2 : '', arr.slice(-1)));
}
/*
arr: data array
s1: regular seperator (string)
s2: last seperator (string)
*/
function customJoin(arr,s1,s2){
return(arr.slice(0,-1).join(s1).concat(arr.length > 1 ? s2 : '', arr.slice(-1)));
}
let arr1 = ['a','b','c','d'];
let arr2 = ['singleToken'];
console.log(customJoin(arr1,',',' and '));
//expected: 'a,b,c and d'
console.log(customJoin(arr1,'::',' and finally::'));
//expected: 'a::b::c and finally::d'
console.log(customJoin(arr2,',','and '));
//expected: 'singleToken'
回答by abagmut
For me the simplest solution is:
对我来说,最简单的解决方案是:
['1', '2', '3'].reduce((previous, current, index, array) => {
if (index === array.length - 1) {
return previous + ' & ' + current;
} else {
return previous + ', ' + current;
}
})
回答by Maxime Lechevallier
In-line solution using reduce:
使用 reduce 的在线解决方案:
[1, 2, 3, 4, 5].reduce((text, value, i, array) => text + (i < array.length - 1 ? ', ' : ' or ') + value);
=> 1, 2, 3, 4 or 5"