Home >Web Front-end >JS Tutorial >Detailed explanation of JavaScript splice() method_Basic knowledge

Detailed explanation of JavaScript splice() method_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 17:16:201287browse

Definition and Usage
The splice() method is used to insert, delete or replace elements of an array.
Syntax
arrayObject.splice(index,howmany,element1,...,elementX)
Parameter Description
index Required. Specifies where to add/remove elements.
This parameter is the subscript of the array element to start inserting and/or deleting, and must be a number.

howmany Required. Specifies how many elements should be removed. Must be a number, but can be "0".
If this parameter is not specified, all elements starting from index to the end of the original array will be deleted.

element1 Optional. Specifies the new element to be added to the array. Insertion begins at the index pointed to by index.
elementX Optional. Several elements can be added to the array.
Return Value
If an element is deleted from arrayObject, the array containing the deleted element is returned.
Description
The splice() method removes zero or more elements starting at index and replaces those removed elements with one or more values ​​declared in the parameter list.
Tips and Notes
Note: Please note that the splice() method has different functions from the slice() method. The splice() method will directly modify the array.
Example
Example 1
In this example we will create a new array and add an element to it:

Copy code The code is as follows:



Output:
George,John, Thomas,James,Adrew,Martin George,John,William,Thomas,James,Adrew,Martin
Example 2
In this example we will delete the element at index 2 and add a new element to replace the deleted element Elements:
Copy code The code is as follows:



Output:
George,John,Thomas,James,Adrew,Martin George,John,William,James,Adrew,Martin
Example 3
In this example we will delete the index from index 2 ("Thomas") and add a new element ("William") to replace the deleted element:
Copy code The code is as follows:



Output:
George,John,Thomas,James,Adrew,Martin George,John, William,Martin
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn