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

高洛峰
Release: 2017-01-03 16:17:33
Original
1427 people have browsed it

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]);
Copy after login

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>
Copy after login

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
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template