Javascript 将数组从 startIndex 连接到 endIndex

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10342728/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 00:57:12  来源:igfitidea点击:

Join Array from startIndex to endIndex

javascriptarraysjoinindexing

提问by globalworming

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 :)

我想问一下是否有某种实用函数可以在提供索引的同时提供数组连接。也许 jQuery 的 Prototype 提供了这个,如果没有,我会自己写 :)

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"

所以 array.join("-", 1, 2) 将返回 "bc"

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

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

Regards Wormi

问候蠕虫

回答by muffel

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

回答by Elliot Bonneville

Just slice the array you want out, then join it manually.

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

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

Note: slice()doesn't include the last index specified, so (1, 3) is equivalent to (1, 2).

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