The shortest and easiest way to understand a js Array operation

  • 2020-03-30 00:46:28
  • OfStack

The method of Array
1 array.join (): returns all the elements as a string, if the element is not of a primitive type, call toString first.
It corresponds to a string. The split ();
Arr = [1, 2, true, three, four, five];
(arr. Join (' - ') = = '1-2 - true - 3-4-5.

2 array.reverse (): arrays in reverse order
Arr = [1, 2, true, three, four, five];
Arr. Reverse (); / / arr = = [5, 3, true, 2, 1];

3 array.sort (): sort, you can pass a sort function as an argument
Arr. Sort (function (a, b) {
      Return a - b;
});

4 Array. Concat (): concatenation function,
Splicing a new element at the end returns the spliced array, but does not change the original array. The argument can be an element, multiple elements, an array,
If it's one element, or more than one element, you just add those elements to the end, and if it's an array, you take the elements out of the array and splice them to the end.
A = [1, 2, 3];
A.c oncat (4, 5) / / return [1, 2, 3, 4, 5]
A.c oncat ([4, 5)) / / return [1, 2, 3, 4, 5]
A.c oncat ([4, 5], [6, 7]); / / return,2,3,4,5,6,7 [1]
A.c oncat ([4, 5, 6]]) / / return [1, 2, 3, 4, [5, 6]] / / attention

Slice (startPos, endPos): takes the substring function (the original Array remains unchanged)
Starting from startPos to the end of endPos but not including the elements on the endPos
If there is no endPos, the tail is taken
If pos is negative, count backwards
A = [1, 2, 3, 4, 5];
A.s lice (0, 3) / / return [1, 2, 3]
A.s lice (3) / / return (4, 5)
A/s (1,-1)//return [2,3,4]// start with the first one and go to the reciprocal, but not the reciprocal
A.s lice (1, 2); //return [2,3]//

Array. Splice (startPos, length, [added1, added2...] ) random access function
You can delete a random element, you can add some elements,
If there are only two arguments, the total length of the elements from startPos is removed from the array
If there are more than two arguments, the total length of the elements from startPos is removed from the array, and the next element is added from the place where it was dropped
If the element to be added is an array, use the array as an element (as opposed to concat)
A = [1, 2, 3, 4, 5];
A.s plice (1, 2) / / return [2, 3]. A = =].enlighened
,2,6,7,8 a.s plice (1) / / return [2, 3]. A = =,6,7,8,4,5 [1]
A.s plice (1, 2, June). / / return [2, 3]; A = = [1, June, 4, 5)

7 Array. Push () and Array. Pop ();
Push is adding,pop is removing and returning the last element

8 Array. The unshift () and Array. The shift ()
Unshift is adding, and shift is removing and returning the first element

combined
These methods change the array:reverse, sort, splice, push, pop, unshift, shift
These methods do not change the original array:join, concat, splice


Related articles: