Javascript数组到句子

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/

  • 我可以看到这个方法有几个问题.如果数组中只有1个元素,它将返回"和Susy".对于两个元素,它返回"Susy和John",这在语法上是不正确的. (4认同)

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".


Prz*_*mek 6

使用最新的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)

  • 哇,当它得到支持时,这会很棒!https://developers.google.com/web/updates/2018/12/intl-listformat (2认同)

Ale*_*lex 5

在这种情况下,还有一些其他情况:

  1. 我们是否要在“和”(牛津逗号)前加逗号?
  2. 无论哪种方式,如果只有2个元素,我们都不希望使用逗号
  3. 如果只有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;
}
Run Code Online (Sandbox Code Playgroud)


Fel*_*e84 5

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)