Deep copies of arrays and objects

Source: Internet
Author: User

One, deep copy of the array

  var arr = ["One", "one", "three"];

var arrcopy = arr;

ARRCOPY[1] = "Test";

Console.log (arr); //["One", "Test", "three"]

Console.log (arrcopy); //["One", "Test", "three"]

1. If you assign an array to another array, change one and the other will change, which is a shallow copy of the array.

2. Solution: Using the slice and concat methods of arrays, both methods produce a new array without altering the original array.

    var arr = ["One", "one", "three"];

var arrcopy = arr.slcie (0); //Arrcopy = Arr.concat ();

ARRCOPY[1] = "Test";

Console.log (arr); //["One", " One", "three"]

Console.log (arrcopy); //["One", "Test", "three"]

Second, deep copy of the object

  var json = {name: "AAA", age:12};

var jsoncopy = json;

Jsoncopy.name = "BBB";

Console.log (JSON); //{name: "BBB", Age:12}

Console.log (jsoncopy); //{name: "BBB", Age:12}

1. Similarly, objects such as direct assignment are also shallow copies .

2. Solution: It is to iterate over the object's properties and assign it to a new object.

    var json = {name: "AAA", age:12};

var jsoncopy = new Object ();

Jsoncopy.name = Json.name;

Jsoncopy.age = Json.age;

Jsoncopy.name = "BBB";

Console.log (JSON); //{name: "AAA", Age:12}

Console.log (jsoncopy); //{name: "BBB", Age:12}

  

  var deepcopy = function (source) {
var result={};
for (var key in source) {
Result[key] = typeof source[key]=== ' object '? Deepcopy (Source[key]): Source[key];
}
return result;
}

Deep copies of arrays and objects

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.