我想要的是像Array.join(separator)
,但它需要第二个参数Array.join(separator, beforeLastElement)
,所以当我说[foo, bar, baz].join(", ", " or")
我会得到"foo, bar or baz"
。我想我可以编写一个使用Array.slice
来分离最后一个元素的函数,但是有一些我可以使用的众所周知的方法吗?
不,这很具体,你必须编写一个自定义函数。好消息是,正如你所说,一旦你使用Array.join
来处理所有的分隔符,最后一个将很容易更新。
使用reduce功能的在线解决方案:
[1, 2, 3, 4, 5].reduce((text, value, i) => !i ? value : `${text}, ${value}`, '');
==> "1, 2, 3, 4, 5"
没有预定义的功能,因为它非常简单。
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(", ");
}
所以在userland中让这个问题似乎更好。
我可以建议:
['tom', 'dick', 'harry'].join(', ').replace(/, ([^,]*)$/, ' and $1')
> "tom, dick and harry"
建立@ 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;
}
示例用法:
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"
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"
有一个包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
紧凑版:)
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'
虽然它是一个迟到的答案,添加一些方法。
方法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
方法2:使用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
对我来说,最简单的解决方案是:
['1', '2', '3'].reduce((previous, current, index, array) => {
if (index === array.length - 1) {
return previous + ' & ' + current;
} else {
return previous + ', ' + current;
}
})