Home > Web Front-end > JS Tutorial > body text

What is the splice() method in JS?

coldplay.xixi
Release: 2020-07-02 11:23:12
Original
5434 people have browsed it

The splice() method adds or removes items from the array and then returns the deleted item. This method will change the original array. The syntax is [arrayObject.splice(index,howmany,item1,.... .,itemX)].

What is the splice() method in JS?

The splice() method in JS is:

1. Definition and usage

splice() The method adds/removes items from the array and then returns the deleted item.

Note: This method will change the original array.

2. Syntax

arrayObject.splice(index,howmany,item1,.....,itemX)
Copy after login

3. Description

  • 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.

  • If an element is deleted from arrayObject , the array containing the deleted element is returned.

5. Example

Example 1

In this example, we will create a new array and add it to Add an element:

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

Output:

George,John,Thomas,James,Adrew,Martin
George,John,William,Thomas,James,Adrew,Martin
Copy after login

Example 2

In this example we will delete the element at index 2 and add a new element to replace the deleted element Elements:

<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,1,"William")
document.write(arr)
</script>
Copy after login

Output:

George,John,Thomas,James,Adrew,Martin
George,John,William,James,Adrew,Martin
Copy after login

Related learning recommendations: javascript video tutorial

The above is the detailed content of What is the splice() method in JS?. For more information, please follow other related articles on the PHP Chinese website!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!