Home >Web Front-end >JS Tutorial >Detailed explanation of the use of splice() method in JavaScript

Detailed explanation of the use of splice() method in JavaScript

高洛峰
高洛峰Original
2017-01-03 16:17:331430browse

The splice() method of JavaScript array changes the contents of the array, adding new elements and eliminating old elements.
Syntax

array.splice(index, howMany, [element1][, ..., elementN]);

The following are the details of the parameters:

Index: The array starting to change at this index.

howMany: Integer, indicating the number of old array elements to remove. If howmany is 0, no elements are removed.

element1, ..., elementN: Elements are added to the array. If no elements are specified, concatenation simply removes elements from the array.

Return value:

Returns an array extracted based on the passed parameters.
Example:

<html>
<head>
<title>JavaScript Array splice Method</title>
</head>
<body>
<script type="text/javascript">
var arr = ["orange", "mango", "banana", "sugar", "tea"];
 
var removed = arr.splice(2, 0, "water");
document.write("After adding 1: " + arr );
document.write("<br />removed is: " + removed);
 
removed = arr.splice(3, 1);
document.write("<br />After adding 1: " + arr );
document.write("<br />removed is: " + removed);
 
</script>
</body>
</html>

This will produce the following results:

After adding 1: orange,mango,water,banana,sugar,tea
removed is:
After adding 1: orange,mango,water,sugar,tea
removed is: banana

More Please pay attention to the PHP Chinese website for related articles on the use of the splice() method in JavaScript!

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