如何在Javascript中将数组(例如["Susy", "John", "Mary"]
)转换为"Susy, John, and Mary"
?我无法理解Ruby的to_sentence方法。
答案 0 :(得分:8)
加入除最后一项之外的所有项目,然后添加:
var s = arr.slice(0, arr.length - 1).join(', ') + ", and " + arr.slice(-1);
答案 1 :(得分:8)
使用Array.prototype.reduce
的另一个选项是:
var arr = [1,2,3];
arr.reduce(
function(prev, curr, i){
return prev + curr + ((i===arr.length-2) ? ' and ' : ', ')
}, '')
.slice(0, -2);
制作"1, 2 and 3"
。
答案 2 :(得分:4)
这一个案例中有一些额外的案例:
我认为这适用于所有这些用例:
function joinSentence( array, oxford_comma ){
if( array.length > 1 ){
var lastWord = " and " + array.pop();
if( oxford_comma && array.length > 1 ){
lastWord = "," + lastWord;
}
}else{
var lastWord = "";
}
return array.join(", ") + lastWord;
}
答案 3 :(得分:4)
使用最新的JavaScript(Chrome 72 +):
new Intl.ListFormat().format(["Susy", "John", "Mary"]);
这将导致:
"Susy, John, and Mary"
答案 4 :(得分:3)
toSentence = function(arr){ return arr.join(", ").replace(/,\s([^,]+)$/, ' and $1');};
toSentence(['dogs', 'cats']); // => dogs and cats
toSentence(['dogs', 'cats', 'snakes']); // => dogs, cats and snakes
答案 5 :(得分:2)
修改最后一个然后加入
var source = ["Susy", "John", "Mary"];
source.push( 'and ' +source.pop());
console.log(source.join(', '))// Susy, John, and Mary
答案 6 :(得分:2)
试试:
var array = ['susy', 'john', 'mary'];
var last = array.pop();
var string = array.join(', ') + " and " + last;
我没试过,但你应该明白这个想法
答案 7 :(得分:1)
您可以使用.join()并使用“and”
添加最后一个值var array = ['susy', 'john', 'mary'];
array[array.length-1] = 'and '+array[array.length-1];
//string is "susy, john, and mary"
var string = array.join(', ');
答案 8 :(得分:1)
另一种解决方案:
(function(a) {
var b = (a||(a=[])).pop();
return (b ? a.length ? [a.join(", "),b] : [b] : a).join(" and ");
})(["Susy", "John", "Mary"]);
或者只是在数组的原型中定义类似ruby的句子方法:
Array.prototype.sentence = function(comma,and) {
var b = this.pop();
return (b ? this.length ? [this.join(comma||", "),b] : [b] : this).join(and||" and ");
};
["Susy", "John", "Mary"].sentence();
//"Susy, John and Mary"
["Susy", "John", "Mary"].sentence(" and ", " as well as ");
//"Susy and John as well as Mary"
["Susy", "John", "Mary", "Helmut"].sentence();
//"Susy, John, Mary and Helmut"
答案 9 :(得分:-1)
var arr = ["Susy", "John", "Mary"];
var str = arr.join(", ");