Attach an array from startIndex to endIndex

I wanted to ask if there is some kind of utility function that offers array union when providing an index. Maybe the jQuery prototype provides this, if not, I will write it myself :)

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) returns "bc"

Is there such a utility feature in a fairly common JavaScript library?

Relations Wormi

+6
source share
2 answers

He works with his native

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

If you want it to behave as your definition, you can use it this 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) //cd arr.myJoin("-") //abcd arr.myJoin("-",1) //bcd 
+26
source

Just draw the array you want, then attach it manually.

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

Note: slice() does not contain the last specified pointer, therefore (1, 3) is equivalent to (1, 2).

+1
source

Source: https://habr.com/ru/post/914279/


All Articles