Is there a way to join the elements in an js array, but let the last separator be different?

前端 未结 11 785
灰色年华
灰色年华 2021-02-03 17:40

What I want is something like Array.join(separator), but which takes a second argument Array.join(separator, beforeLastElement), so when I say [f

11条回答
  •  执念已碎
    2021-02-03 18:06

    Building off of @dystroy's answer:

    function formatArray(arr){
        var outStr = "";
        if (arr.length === 1) {
            outStr = arr[0];
        } else if (arr.length === 2) {
            //joins all with "and" but no commas
            //example: "bob and sam"
            outStr = arr.join(' and ');
        } else if (arr.length > 2) {
            //joins all with commas, but last one gets ", and" (oxford comma!)
            //example: "bob, joe, and sam"
            outStr = arr.slice(0, -1).join(', ') + ', and ' + arr.slice(-1);
        }
        return outStr;
    }
    

    Example usages:

    formatArray([]);                //""
    formatArray(["a"]);             //"a"
    formatArray(["a","b"]);         //"a and b"
    formatArray(["a","b","c"]);     //"a, b, and c"
    formatArray(["a","b","c","d"]); //"a, b, c, and d"
    

提交回复
热议问题