Copy codeThe Code is as follows:
Array. prototype. ArrayInsertAfter = function (Num, obj)
{
Var tempArr = new Array ();
Var l = this. length;
For (var I = 0; I <l; I ++)
{
TempArr. push (this. shift ());
}
L = tempArr. length;
For (var I = 0; I <l; I ++)
{
This. push (tempArr. shift ());
If (I = Num)
{
This. push (obj );
}
}
Return this;
}
How to use JavaScript splice ()
Definition and usage
The splice () method is used to insert, delete, or replace elements in an array.
Syntax
ArrayObject. splice (index, howmany, element1,..., elementX)
Parameters |
Description |
Index |
Required. Specifies where to add/delete elements. This parameter is the subscript of the array element that begins to insert or delete. It must be a number. |
Howmany |
Required. Specifies how many elements should be deleted. It must be a number, but it can be "0 ". If this parameter is not specified, all elements starting from index to the end of the original array are deleted. |
Element1 |
Optional. Specifies the new element to be added to the array. Insert from the subscript indicated by index. |
ElementX |
Optional. You can add several elements to the array. |
Return Value
If an element is deleted from an arrayObject, an array containing the deleted element is returned.
Description
The splice () method deletes zero or multiple elements starting from the index and replaces the deleted elements with one or more values declared in the parameter list.
Tips and comments
Note: The splice () method and slice () method have different functions. The splice () method directly modifies the array.
Instance
Example 1
In this example, we will create a new array and add an element to it:
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Output:
George, John, Thomas, James, Adrew, Martin
George, John, William, Thomas, James, Adrew, Martin
Example 2
In this example, we will delete the Element Located in index 2 and add a new element to replace the deleted element:
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Output:
George, John, Thomas, James, Adrew, Martin
George, John, William, James, Adrew, Martin
Example 3
In this example, we will delete the three elements starting with index 2 ("Thomas") and add a new element ("William") to replace the deleted element:
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]
Output:
George, John, Thomas, James, Adrew, Martin
George, John, William, Martin