Js array operation learning summary

  • 2020-03-26 23:07:41
  • OfStack

Shift: Deletes the first item of the original array and returns the value of the deleted element. Returns undefined if the array is empty
Var a = [1, 2, 3, 4, 5].
Var b = a.s hift ();        

Result a: [2,3,4,5]        B: 1.


Unshift: adds an argument to the beginning of the original array and returns the length of the array
Var a = [1, 2, 3, 4, 5].
Var b = a.u nshift (2, 1);

Result a: [-2,-1, 1,1,2,3,4,5]          B: 7

Note: the test return value under IE6.0 is always undefined, and the test return value under FF2.0 is 7. Therefore, the return value of this method is not reliable. Splice can be used instead of this method when the return value is used.


Pop: Deletes the last item in the original array and returns the value of the deleted element. Returns undefined if the array is empty
Var a = [1, 2, 3, 4, 5].
Var b = Amy polumbo op ();

Results   A: [1, 2, 3, 4]   B: 5


Push: adds an argument to the end of the original array and returns the length of the array
Var a = [1, 2, 3, 4, 5].
Var b = Amy polumbo ush (6, 7);

Result a: [1,2,3,4,5,6,7]    B: 7


Concat: Returns a new array formed by adding arguments to the original array
Var a = [1, 2, 3, 4, 5].
Var b = a.c oncat (6, 7);

Result a: [1,2,3,4,5]    B:,2,3,4,5,6,7 [1]


Splice (start, deleteCount, val1, val2,...). : delete the deleteCount item from the start position and insert val1,val2...
Var a = [1, 2, 3, 4, 5].
Var b = a.s plice,2,7,8,9 (2);

Result a: [1,2,7,8,9,5]    B: [3, 4]

Var b = a.s plice (0, 1);                                                                           / / the same shift
A.s plice (0, 0, 2, 1);   Var b = a. ength;                                         / / with the unshift
Var b = a.s plice (a. ength - 1, 1);                                                         / / with pop
A.s plice (a. ength, 0, 6); Var b = a. ength;                                 / / with a push

Reverse: Reverse order the array
Var a = [1, 2, 3, 4, 5].
Var b = a.r everse ();

Results   A: [5,4,3,2,1]       B:,4,3,2,1 [5]


Sort (orderfunction) : Sorts the array by the specified parameters
Var a = [1, 2, 3, 4, 5].
Var b = a.s ort ();

Result a: [1,2,3,4,5]      B: [1, 2, 3, 4, 5]


Slice (start, end) : Returns a new array of items from the original array that specify the starting and ending subscripts
Var a = [1, 2, 3, 4, 5].
Var b = a.s lice (2, 5);

Result a: [1,2,3,4,5] b: [3,4,5]


The join (separator) : Group the elements of an array into a string, separator, with the default comma separator for omission
Var a = [1, 2, 3, 4, 5].
Var b = a. oin (" | ");

Result a: [1,2,3,4,5] b: "1|,2 |,3 |,4 |,5"


Related articles: