JavaScript copy Array

Source: Internet
Author: User

Several methods of commonly used replicated arrays

Direct ARR1 = Arr2 This method copies a reference to the original array, and modifying the copied new array changes the contents of the original array.

var arr = [1, 2, 3, 6];var arr_ = Arr;console.log (arr_);//1,2,3,6arr_.splice (2, 0, 4, 5); Console.log (ARR_);//1,2,3,4,5,6;c Onsoe.log (arr);//1,2,3,4,5,6;

Because the copy is a reference to an array, the original array is changed, and the original array can be changed as well. Here's an example of Xiaoice

var array1 = new Array ("1", "2", "3"); var array2; Array2 = array1; array1.length = 0; alert (array2); Return to Empty

A good practice, in addition to using for To loop, you can also use the slice () method or the Concat () method to operate the array

var arr1 = [1, 2, 3];var arr2 = arr1.slice (0); Arr2.splice (3,0,4,5); Console.log (ARR2);//1,2,3,4,5console.log (arr1);// The

  

var arr1 = [1, 2, 3];var arr2 = Arr1.concat ([]); Arr2.splice (3,0,4,5); Console.log (ARR2);//1,2,3,4,5console.log (arr1);// The

Because Slice and concat return a new array, these two methods can be used for replication

JavaScript copy Array

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.