Join Array from startIndex to endIndex

后端 未结 2 371
深忆病人
深忆病人 2021-01-11 10:52

I wanted to ask if there is some kind of utility function which offers array joining while providing an index. Maybe Prototype of jQuery provides this, if not, I will write

2条回答
  •  别那么骄傲
    2021-01-11 11:40

    It works native

    ["a", "b", "c", "d"].slice(1,3).join("-") //b-c
    

    If you want it to behave like your definition you could use it that way:

    Array.prototype.myJoin = function(seperator,start,end){
        if(!start) start = 0;
        if(!end) end = this.length - 1;
        end++;
        return this.slice(start,end).join(seperator);
    };
    
    var arr = ["a", "b", "c", "d"];
    arr.myJoin("-",2,3)  //c-d
    arr.myJoin("-") //a-b-c-d
    arr.myJoin("-",1) //b-c-d
    

提交回复
热议问题