1. Deep-copy json.stringify () and json.parse ()
let obj1 = {"a": {"b": [1.2.3, {"c": 4}},"d": [5.6, {"e": [7.8.9]}]};
let obj2 = JSON.parse(JSON.string(obj1));
let arr1 = [1.2, {"a": 3."b": [4.5, {"d": 6}}], [7[8[9, {"e": {"f": 10}}]]]];
let arr2 = JSON.parse(JSON.string(obj1));
Copy the code
Parse (json.stringify (obj)) is used to serialize the JS object using json.stringify (obj), and then use json.parse to deserialize (restore) the JS object.
Disadvantages: Time, re, function, Error, NaN cannot be converted, only array, object, number, string
2. Deep copy function
let data = ["a", {"a1": function(){}},1.2.3[4.5.6]], new RegExp('\\w+')];
function judjeType(data) {
return Object.prototype.toString.call(data);
}
function deepClone(data) {
let newData = null;
let type = judjeType(data);
if (type == "[object Object]") {
newData = {};
for (let key indata) { newData[key] = deepClone(data[key]); }}else if (type == "[object Array]") {
newData = [];
for (var i = 0; i < data.length; i++) {
newData.push(deepClone(data[i]))
}
} else {
return data;
}
return newData;
}
deepClone(data);
Copy the code
Code at execution time, every time when you meet the new array or object will generate a new subset (is) from the dimension of the code, not because there are new newData before data can not find, here it is easy to understand deviation, for example, just Russian dolls games, the outermost layer is the first for loop (can be an array object), When a new array or object is found, a new subset will be generated, just like a smaller doll is generated in the outermost doll. If there are still objects or arrays, the generation will continue. After the generation, a result will be returned to the upper level, until the end of the outermost loop to get the final result.
3. {… } and […].
{… } and […]. Both are shallow copies, which can only copy the first layer of the object and array, and the second layer, including the second layer, cannot be copied.
let obj1 = {"a": {"b": [1.2.3, {"c": 4}},"d": [5.6, {"e": [7.8.9]}], "f": 10};
letobj2 = {... obj1}; obj1.a.b[0] = 0;
obj1.f = 11;
console.log(obj1, obj2)
/ / obj1 = {" a ": {" b" : [0, 2, 3, 4} {" c ":]}," d ": [5, 6, {" e" :,8,9 [7]}], "f" : 11};
/ / obj2 = {" a ": {" b" : [0, 2, 3, 4} {" c ":]}," d ": [5, 6, {" e" :,8,9 [7]}], "f" : 10};
let arr1 = [1.2, {"a": 3."b": [4.5, {"d": 6}}], [7[8[9, {"e": {"f": 10}}]]]];
let arr2 = [...arr1];
arr1[0] = 0;
arr1[2].b[0] = 44;
console.log(arr1, arr2)
/ / arr1 = [0, 2, {" a ": 3," b ": [44, 5, {6}" d ":]}, [7, [8, [9, {" e" : {" f ": 10}}]]]].
/ / arr2 = [1, 2, {" a ": 3," b ": [44, 5, {6}" d ":]}, [7, [8, [9, {" e" : {" f ": 10}}]]]].
Copy the code