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