Javascript comma list but has an and at the last one

前端 未结 3 760
别那么骄傲
别那么骄傲 2021-01-17 09:30

I am trying to create a function that will take a list of words -- and covert it into a sentence like this.

jsfiddle

http://jsfiddle.net/0ht35rpb/107/

<
相关标签:
3条回答
  • 2021-01-17 09:42

    This should work.

    function createSentence(array) {
      if (array.length == 1) {
        return array[0];
      } else if (array.length == 0) {
        return "";
      }
      var leftSide = array.slice(0, array.length - 1).join(", ");
      return leftSide + " and " + array[array.length - 1];
    }
    
    console.log(createSentence(["dogs", "cats", "fish"]));
    console.log(createSentence(["dogs", "cats"]));
    console.log(createSentence(["dogs"]));
    console.log(createSentence([]));

    0 讨论(0)
  • 2021-01-17 09:46

    One way is to pop off the last item, and then join and place the last item within the sting

    function grammarCheck(vals) {
          //x,y,z and d
          //z
          var count = vals.length;
    
          var last = vals.pop()
          
          var text = vals.join(', ') + (vals.length > 1 ? ' and ' : '') + last
    
          return text
        }
        
        
        var arr = [
              ["emotional distress"],
              ["abc", "123", "blah", "blah", "blah"]
        ]
        
        arr.forEach(a => console.log('grammar check', grammarCheck(a)))

    0 讨论(0)
  • 2021-01-17 09:52

    The function you have commented out seems to be right, except that it's using some property off this rather than the parameter passed to it.

    Adjusting that, you get this:

    const grammarCheck = function(vals) {
      return [ vals.slice(0, -1).join(", "), vals.slice(-1)[0] ]
             .join(vals.length < 2 ? "" : " and ");
    }
    grammarCheck(['foo']); //=> 'foo'
    grammarCheck(['foo', 'bar']); //=> 'foo and bar'
    grammarCheck(['foo', 'bar', 'baz']); //=> 'foo, bar and baz'
    grammarCheck(['foo', 'bar', 'baz', 'qux']); //=> 'foo, bar, baz and qux'
    

    Obviously, you could alter this a bit if you want the Oxford comma.

    0 讨论(0)
提交回复
热议问题