18

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 it on my own :)

What I expect is something like

var array= ["a", "b", "c", "d"];
function Array.prototype.join(seperator [, startIndex, endIndex]){
  // code
}

so that array.join("-", 1, 2) would return "b-c"

Is there this kind of utility function in an pretty common Javascript Library?

Regards
globalworming

4

2 に答える 2

58

ネイティブで動作します

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

定義のように動作させたい場合は、次のように使用できます。

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
于 2012-04-26T23:20:39.337 に答える
5

必要な配列をスライスしてから、手動で結合するだけです。

var array= ["a", "b", "c", "d"];
var joinedArray = array.slice(1, 3).join("-");

注:slice()最後に指定されたインデックスは含まれないため、(1、3)は(1、2)と同等です。

于 2012-04-26T23:20:47.897 に答える