Experience the powerful (insert, delete, or replace elements of an array) in JS splice () _javascript Tips

Source: Internet
Author: User
There are many ways to handle arrays, and JavaScript splice () is the most powerful, and it can be used to insert, delete, or replace elements of an array. Here are the introductions!

1. Delete-To delete the element, two parameters, the first argument (to delete the position of the first item), the second argument (number of items to delete)
2. Insert-Inserts any item element into the array at the specified position. Three parameters, first argument (in fact, position), second argument (0), third argument (inserted item)
3. Replace-inserts any item element into the array at the specified position, deleting any number of items, and three parameters. First argument (starting position), second argument (number of deleted items), third argument (inserts any number of items)

Look at the code below and you'll see.
Copy Code code as follows:

var lang = ["PHP", "Java", "JavaScript"];
Delete
var removed = Lang.splice (1,1);
alert (lang); Php,javascript
alert (removed); Java, returning Deleted Items
Insert
var insert = Lang.splice (0,0, "ASP"); Insert starting from No. 0 position
alert (insert); Returns an empty array
alert (lang); Asp,php,javascript
Replace
var replace = Lang.splice (1,1, "C #", "Ruby"); Delete an item, insert two items
alert (lang); Asp,c#,ruby
alert (replace); PHP, returning the deleted item

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.