Cor*_*rey 11 javascript jquery
我怎么能拒绝一个数组,如["Susy", "John", "Mary"]要"Susy, John, and Mary"在Javascript?我无法理解Ruby的to_sentence方法.
Guf*_*ffa 10
加入除最后一项之外的所有项目,然后添加:
var s = arr.slice(0, arr.length - 1).join(', ') + ", and " + arr.slice(-1);
Run Code Online (Sandbox Code Playgroud)
演示:http://jsfiddle.net/JYKcK/1/
Rui*_*mos 10
使用的另一个选择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);
Run Code Online (Sandbox Code Playgroud)
生产"1, 2 and 3".
使用最新的JavaScript(Chrome 72+):
new Intl.ListFormat().format(["Susy", "John", "Mary"]);
Run Code Online (Sandbox Code Playgroud)
这将导致:
"Susy, John, and Mary"
Run Code Online (Sandbox Code Playgroud)
在这种情况下,还有一些其他情况:
我认为这适合所有这些用例:
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;
}
Run Code Online (Sandbox Code Playgroud)
toSentence = function(arr){ return arr.join(", ").replace(/,\s([^,]+)$/, ' and $1');};
toSentence(['dogs', 'cats']); // => dogs and cats
toSentence(['dogs', 'cats', 'snakes']); // => dogs, cats and snakes
Run Code Online (Sandbox Code Playgroud)