In the eyes of many students, the splice () method may be used to divide strings into arrays. In fact, it can not only implement this function, but also delete or replace array elements, I will introduce it to you below.
Requirement: array arr2 is used to encapsulate the plug-in to overwrite all elements in array arr1.
Definition and usage
The splice () method is used to insert, delete, or replace elements in an array.
Syntax
ArrayObject. splice (index, howmany, element1,..., elementX)
Example 1
In this example, we will create a new array and add an element to it:
The Code is as follows: |
Copy code |
<Script type = "text/javascript"> Var arr = new Array (6) Arr [0] = "George" Arr [1] = "John" Arr [2] = "Thomas" Arr [3] = "James" Arr [4] = "Adrew" Arr [5] = "Martin" Document. write (arr + "<br/> ") Arr. splice (2, 0, "William ") Document. write (arr + "<br/> ") </Script> output: George, John, Thomas, James, Adrew, Martin George, John, William, Thomas, James, Adrew, Martin |
Okay, the above is just a brief introduction to the source code. Next we will introduce the method of splice () to overwrite the array.
Instance source code
The Code is as follows: |
Copy code |
<Div id = "demo"> </div> <Script type = "text/javascript"> Var arr1 = ["element 1", "element 2"]; Var arr2 = ["arr2-element 1", "arr2-element 2"]; Arr1.splice (0, arr1.length, arr2 ); Document. getElementById ("demo"). innerHTML = arr1; </Script> |