Detailed JavaScript in Splice () method

Source: Internet
Author: User

Splice () method is a less useful method, but the function is really good, and in our coding, often need to splice () method, first introduce this method.

The splice () method in JavaScript is a strong array method that has many uses.

The splice () method is primarily used to add new values to the array.

1, delete (requires 2 parameters, the first parameter is "start bit", the second parameter indicates the number of deleted)

 1  //  Create array  2  var array = [];  3  //  add value  4  array.push (1 5  array.push (2 6  array.push (3 7  //  Delete, from No. 0 To start, delete an element.  8  array.splice (0,1 9  console.log (array); //  

2, insert/Add value (when adding or inserting values into an array, we need 3 parameters, the first is "start bit", the second is "number of elements to delete" and the second is: "Items to insert")

1 //Create an array2var array = [];3 //Add Value4Array.push (1);5Array.push (2);6Array.push (3);7 //adds or inserts a value to an array. 8Array.splice (1, 1, "Add value 1", "Add Value 2", "Add value 3");9Console.log (array);//The result is: [1, "Add value 1", "Add Value 2", "Add Value 3", 3]

Note : From the first start, which is the position in the original array “2” , then the second parameter represents the deletion of a number 2” , and then the "添加值1","添加值2","添加值3" value to be newly inserted.

If we do not need to delete, then the second parameter is a “0”

3, replace (in fact, the replacement and the second way, in fact, is to insert a few to delete a few, to achieve the effect)

 1  //  Create array  2  var array = [];  3  //  add value  4  array.push (1 5  array.push (2 6  array.push (3 7  //  We replace 2 and 3 with 5 and 6  8  array.splice (1,2,5,6 9  console.log (array); //  

Additional additions: In JavaScript, there are two ways to create an array.

    • var array = [];
    • var array = new Array();

These two ways create the same effect.

Detailed JavaScript in Splice () method

Related Article

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.