Array methods
1 Array.join(): Concatenate all elements into a string using symbols and return it. If the element is not a basic type, call toString first.
It corresponds to string.split();
arr = [1,2,true,3,4,5];
(arr.join('-') == '1-2-true-3-4-5';
2 Array.reverse(): Arrange array in reverse order
arr = [1,2,true,3,4,5];
arr.reverse();// arr == [5,4,3,true,2,1];
3 Array.sort(): Sorting, you can pass a sorting function as a parameter
arr.sort(function(a,b){
return ab;
});
4 Array.concat(): concatenation function,
Splice new elements at the end and return the spliced array without changing the original array; the parameter can be one element, multiple elements, or an array,
If it is one element or multiple elements, add these elements directly to the end. If it is an array, take out each element of the array and splice them to the end.
a = [1,2,3];
a.concat(4,5)// return [1,2,3,4,5]
a.concat([4,5])// return [1,2,3,4,5]
a.concat([4,5],[6,7]);//return [1,2,3,4,5,6,7]
a.concat([4,[5,6]])//return [1,2,3,4,[5,6]]//Note
5 Array.slice(startPos, endPos): substring function (the original array remains unchanged)
Starts from startPos and ends with endPos but does not include the elements on endPos.
If there is no endPos, get to the end
If pos is negative, count backwards
a = [1,2,3,4,5];
a.slice(0,3)// return [1,2,3]
a.slice(3)//return [4,5]
a.slice(1,-1)//return [2,3,4]//Start from the first one, get the first one from the last, but not include the first one from the last
a.slice(1,-2);//return [2,3]//Start from the first one and get to the second to last one, but not including the second to last one
6 Array.splice(startPos, length, [added1, added2...]) Random access function
You can randomly delete one (some) elements or add some elements.
If there are only two parameters, a total of length elements starting from startPos are removed from the array.
If there are more than two parameters, delete a total of length elements starting from startPos from the array, and then add the following elements from the position just deleted.
If the element being added is an array, use the array as an element (difference from concat)
a = [1,2,3,4,5];
a.splice(1,2)//return [2,3]; a==[1,4,5]
a.splice(1,2,6,7,8)//return [2,3]; a==[1,6,7,8,4,5]
a.splice(1,2,[6,7,8]);//return [2,3]; a==[1,[6,7,8],4,5]
7 Array.push() and Array.pop();
Both operate on the last element, push is to add, and pop is to delete the last element and return the element.
8 Array.unshift() and Array.shift()
Both operate on the first element, unshift is to add, shift is to delete the first element and return the element
in total
These methods will change the original array: reverse, sort, splice, push, pop, unshift, shift
These methods do not change the original array: join, concat, splice