Javascript comma list but has an and at the last one

前端 未结 3 763
别那么骄傲
别那么骄傲 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([]));

提交回复
热议问题