如何在 Javascript 中转换数组,例如["Susy", "John", "Mary"]
to ?"Susy, John, and Mary"
我无法摆脱 Ruby 的 to_sentence 方法。
问问题
13500 次
10 回答
16
使用最新的 JavaScript (Chrome 72+):
new Intl.ListFormat().format(["Susy", "John", "Mary"]);
这将导致:
"Susy, John, and Mary"
于 2018-12-05T22:10:35.617 回答
12
加入除最后一项之外的所有项目,然后添加:
var s = arr.slice(0, arr.length - 1).join(', ') + ", and " + arr.slice(-1);
演示:http: //jsfiddle.net/JYKcK/1/
于 2013-02-08T00:59:25.840 回答
11
使用 的另一个选项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"
.
于 2014-02-20T14:24:31.063 回答
6
这其中有几个额外的案例:
- 我们想在“和”之前有一个逗号吗(Oxford Comma)
- 无论哪种方式,如果只有 2 个元素,我们不想要逗号
- 如果只有 1 个元素,我们只希望返回那个词
我认为这适合所有这些用例:
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;
}
于 2014-04-12T05:56:20.683 回答
6
toSentence = function(arr){ return arr.join(", ").replace(/,\s([^,]+)$/, ' and $1');};
toSentence(['dogs', 'cats']); // => dogs and cats
toSentence(['dogs', 'cats', 'snakes']); // => dogs, cats and snakes
于 2014-06-24T01:14:01.417 回答
3
另一个解决方案:
(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"
于 2013-02-08T01:22:54.653 回答
2
修改最后一个然后加入
var source = ["Susy", "John", "Mary"];
source.push( 'and ' +source.pop());
console.log(source.join(', '))// Susy, John, and Mary
于 2013-02-08T01:01:17.457 回答
2
试试看:
var array = ['susy', 'john', 'mary'];
var last = array.pop();
var string = array.join(', ') + " and " + last;
我没试过,但你应该明白
于 2013-02-08T01:01:24.273 回答
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(', ');
于 2013-02-08T00:56:28.690 回答
-2
var arr = ["Susy", "John", "Mary"];
var str = arr.join(", ");
于 2013-02-08T00:57:24.377 回答