The splice () method of array arrays is also a very powerful way to delete, insert, replace
It should be noted that the splice () method modifies the original array directly
I. The use of deletion
Grammar: Array.splice (starti,n);
Starti refers to where to start (not including Starti)
n refers to the number of items that need to be deleted
[HTML] view plain copy <script> var array=[1,2,3,4,5]; Array.splice (3,2); Console.log (array); </script>
Result: [1,2,3]
Here is a small extension: In fact, the deleted elements can be received with a variable, the received variable can be used as a mosaic array
[HTML]View plain copy <script> var array=[1,2,3,4,5]; var deletes =array.splice (3,2); Console.log (deletes); Console.log (array); </script>
Results: [4,5] [1,2,3]
We will delete the elements after the original array is spliced back
[HTML]View plain copy <script> var array=[1,2,3,4,5]; var deletes =array.splice (3,2); Console.log (deletes); Console.log (array); Array=array.concat (deletes); Console.log (array); </script>
Results: [4,5] [1,2,3] [1,2,3,4,5]
Second, the use of insertion
Syntax: Array.splice (starti,0, value 1, value 2 ...);
Starti: Where to insert, the value of the original Starti position to move backward
0: Deletes 0 elements, because both inserts and replacements are expanded by the deletion function.
Value 1, value 2: The value that needs to be inserted
[HTML]View plain copy <script> var array=[1,2,3,4,5]; Array.splice (2,0,123,456); Console.log (array); </script> results: [1,2,123,456,3,4,5]
Third, the use of substitution
Syntax: Array.splice (starti,n, value 1, value 2);
The principle is the same as the use of inserts
The real thing is: Delete the n elements in the Starti position, then insert the value 1 in this position, and the value 2, you can replace
Values that were originally deleted
[HTML] view plain copy <span style= "FONT-SIZE:24PX;" ><script> var array=[1,2,3,4,5]; Array.splice (2,2,123,456); Console.log (array); </script></span>