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

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

    Array.prototype.join2 = function(all, last) {
        var arr = this.slice();                   //make a copy so we don't mess with the original
        var lastItem = arr.splice(-1);            //strip out the last element
        arr = arr.length ? [arr.join(all)] : [];  //make an array with the non-last elements joined with our 'all' string, or make an empty array
        arr.push(lastItem);                       //add last item back so we should have ["some string with first stuff split by 'all'", last item]; or we'll just have [lastItem] if there was only one item, or we'll have [] if there was nothing in the original array
        return arr.join(last);                    //now we join the array with 'last'
    }
    
    > [1,2,3,4].join2(', ', ' and ');
    >> "1, 2, 3 and 4"
    

提交回复
热议问题