Javascript-differences between slice and splice

Source: Internet
Author: User
ArticleDirectory
    • 1. Slice
    • 2. splice

Today, I reviewed JavaScript and saw the array method. Two of them are similar: splice and splice. They look very similar, but they have a P, but their usage is quite different.

1. Slice

Slice is used to create a new array by specifying the elements in an array, that is, the original array will not change

 
VaRColor =NewArray ('red', 'Blue ', 'yellow', 'black');VaRColor2 = color. Slice (1, 2); Alert (color );//OutputRed, blue, yellow, black
Alert (color2 );//OutputBlue; Note: there is only one value for the second item.
2. splice

Splice is the most powerful method of array functions in JS. It can delete, insert, and replace array elements,The returned value is the operated value..

Splice deletion:Color. splice (1, 2)(Delete items 1 and 2 in color );

Splice insert:Color. splice (1, 0, 'Brown ', 'pink ')(Insert two values before the element whose color key value is 1 );

Splice replacement:Color. splice (1, 2, 'Brown ', 'pink ')(Replace element 1 and element 2 in color );

   var  color =  New  array ('red', 'blue', 'yellow ', 'black' );   var  color2 = color. splice (000000, 'Brown ', 'pink' ); alert (color );   //    Red, blue, brown, pink     alert (color2 );  //    yellow, black    
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.