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

Experience the power of splice() in js (inserting, deleting or replacing elements of an array)_javascript skills

WBOY
Release: 2016-05-16 17:43:28
Original
1130 people have browsed it

There are many ways to process arrays, and JavaScript splice() is the most powerful. It can be used to insert, delete, or replace elements of an array. Let’s introduce them one by one!

1. Delete - used to delete elements, two parameters, the first parameter (the position of the first item to be deleted), the second parameter (the number of items to be deleted)
2. Insert -Insert an arbitrary element into the array at the specified position. Three parameters, the first parameter (actual position), the second parameter (0), the third parameter (the inserted item)
3. Replacement - insert any item element into the specified position of the array, and delete any number at the same time item, three parameters. The first parameter (starting position), the second parameter (the number of items to delete), the third parameter (to insert any number of items)

Look at the code below to understand

Copy code The code is as follows:

var lang = ["php","java ","javascript"];
//Delete
var removed = lang.splice(1,1);
alert(lang); //php,javascript
alert(removed); / /java, return the deleted item
//Insert
var insert = lang.splice(0,0,"asp"); //Insert from the 0th position
alert(insert); / /Return empty array
alert(lang); //asp,php,javascript
//Replace
var replace = lang.splice(1,1,"c#","ruby"); // Delete one item and insert two items
alert(lang); //asp,c#,ruby
alert(replace); //php, return the deleted item
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