Using the splice method in javascript, you can easily insert, delete, and replace array elements.

Source: Internet
Author: User
Tags javascript array

During the interview, if the examiner asks you to use JavaScript to insert, delete, and replace array elements. If you do not know the method used by Array. prototype. splice, the score may be deducted. Using the built-in splice method of javascript array type, you can insert, delete, and replace array elements with only one line of code.

Method signature:

Array. prototype. splice (index, count [, elm1, elm2... n])


Array splice can be used to insert, replace, and delete Array elements. This method directly affects the current array object (different from the. slice (index1, index2) method) and returns the deleted array items.


Index: the starting subscript of the element in the array.

Count: number of elements to be deleted or replaced.

Elems: The items to be inserted into the array.

Return Value: return the items removed from the group.


Var items = ["a", "B", "c", "d", "e"];

// Delete an element

Result = items. splice (1, 2)

// This operation deletes the element ["B", "c"] in the items array in the example, and returns ["B", "c"] to result.

// Replace Element

Result = items. splice (1, 2, "x", "y ")

// This operation uses the element "x" and "y" to replace the element ["B", "c"] in the items array in the example, and returns ["B ", "c"] to result.

// Insert element

Result = items. splice (1, 0, "x", "y ")

// The result of this operation is to insert ["x", "y"] after the "B" element of the items array in the example. The return value is null.


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