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

前端 未结 11 774
灰色年华
灰色年华 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:03

    compact version :)

    function customJoin(arr,s1,s2){
    return(arr.slice(0,-1).join(s1).concat(arr.length > 1 ? s2 : '', arr.slice(-1)));
    }
    

    /* 
    arr: data array
    s1: regular seperator (string)
    s2: last seperator (string)
    */
    
    function customJoin(arr,s1,s2){
    return(arr.slice(0,-1).join(s1).concat(arr.length > 1 ? s2 : '', arr.slice(-1)));
    }
    
    let arr1 = ['a','b','c','d'];
    let arr2 = ['singleToken'];
    
    console.log(customJoin(arr1,',',' and '));
    //expected: 'a,b,c and d'
    console.log(customJoin(arr1,'::',' and finally::'));
    //expected: 'a::b::c and finally::d'
    console.log(customJoin(arr2,',','and '));
    //expected: 'singleToken'

提交回复
热议问题