Splice () method is a less useful method, but the function is really good, and in our coding, often need to splice () method, first introduce this method.
The splice () method in JavaScript is a strong array method that has many uses.
The splice () method is primarily used to add new values to the array.
1, delete (requires 2 parameters, the first parameter is "start bit", the second parameter indicates the number of deleted)
1 // Create array 2 var array = []; 3 // add value 4 array.push (1 5 array.push (2 6 array.push (3 7 // Delete, from No. 0 To start, delete an element. 8 array.splice (0,1 9 console.log (array); //
2, insert/Add value (when adding or inserting values into an array, we need 3 parameters, the first is "start bit", the second is "number of elements to delete" and the second is: "Items to insert")
1 //Create an array2var array = [];3 //Add Value4Array.push (1);5Array.push (2);6Array.push (3);7 //adds or inserts a value to an array. 8Array.splice (1, 1, "Add value 1", "Add Value 2", "Add value 3");9Console.log (array);//The result is: [1, "Add value 1", "Add Value 2", "Add Value 3", 3]
Note : From the first start, which is the position in the original array “2”
, then the second parameter represents the deletion of a number “
2”
, and then the "添加值1","添加值2","添加值3"
value to be newly inserted.
If we do not need to delete, then the second parameter is a “0”
3, replace (in fact, the replacement and the second way, in fact, is to insert a few to delete a few, to achieve the effect)
1 // Create array 2 var array = []; 3 // add value 4 array.push (1 5 array.push (2 6 array.push (3 7 // We replace 2 and 3 with 5 and 6 8 array.splice (1,2,5,6 9 console.log (array); //
Additional additions: In JavaScript, there are two ways to create an array.
var array = [];
var array = new Array();
These two ways create the same effect.
Detailed JavaScript in Splice () method