Array to Comma separated string and for last tag use the 'and' instead of comma in jquery

前端 未结 6 975
孤城傲影
孤城傲影 2020-12-05 00:55

I have checked many questions and answers regarding join array with comma separated string, But my problem is that, I am making the string readable for human i.e I have tag

6条回答
  •  有刺的猬
    2020-12-05 01:17

    (note: you may skip to the end to find the final ready-to-pick code)


    The one-liner from Blender's answer works great, though I'd favor something more understandable:

    function arrayToText(a) {
        if (a.length === 0) {
            return '';
        } else if (a.length === 1) {
            return String(a[0]); // cast to string, for consistency with the other cases
        } else if (a.length === 2) {
            return a.join(' and ');
        } else {
            return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
        }
    }
    

    The same using a switch, see how nicer it is to read:

    function arrayToText(a) {
        switch (a.length) {
            case 0:
                return '';
            case 1:
                return String(a[0]); // cast to string, for consistency with the other cases
            case 2:
                return a.join(' and ');
            default:
                return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
        }
    }
    

    Of course, these codes can be shortened/optimized, for example by merging the "0", "1" and "2" cases into just the a.join(' and ') from the case "2". I let you tweak these codes according to your taste :)

    Finally, here is my end result, I think it has a great balance between understandability, shortness and efficiency:

    function arrayToText(a) {
        if (a.length <= 2) {
            return a.join(' and ');
        } else {
            return a.slice(0, -1).join(', ') + ' and ' + a[a.length-1];
        }
    }
    

提交回复
热议问题