将数组从startIndex连接到endIndex

glo*_*ing 11 javascript arrays indexing join

我想询问是否有某种实用功能在提供索引时提供数组连接.也许jQuery的Prototype提供了这个,如果没有,我会自己写:)

我期待的是像

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

这样array.join(" - ",1,2)将返回"bc"

在一个非常常见的Javascript库中是否有这种实用功能?

关心Wormi

muf*_*fel 47

它原生作用

["a", "b", "c", "d"].slice(1,3).join("-") //b-c
Run Code Online (Sandbox Code Playgroud)

如果您希望它的行为与您的定义相同,您可以这样使用它:

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
Run Code Online (Sandbox Code Playgroud)

  • 是的,很好……完全忘记了切片功能。谢谢你们。 (2认同)

Ell*_*lle 5

只需将您想要的数组切片,然后手动加入它。

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

注意:slice()不包括指定的最后一个索引,所以 (1, 3) 等价于 (1, 2)。