Three implementations of JS deep copy
1. Convert the object into a JSON string, and then convert it into a native JS object;
//_tmp and result are independent of each other, have no connection, and have their own storage space. let deepClOne = function (obj) { let _tmp = JSON.stringify(obj);//Convert the object to json string form let result = JSON.parse(_tmp);//Convert the converted string to a native js object return result; }; let obj1 = { weiqiujaun: { age: 20, class: 1502 }, liuxiaotian: { age: 21, class: 1501 } }; let test = deepClone(obj1); console.log(test);
2. Use the for loop in JS to traverse and copy;
function deepClone(obj) { let result = typeof obj. splice === "function" ? [] : {}; if (obj && typeof obj === 'object') { for (let key in obj) { if (obj[key] && typeof obj[key] === 'object') { result[key] = deepClone(obj[key]);//If the attribute value of the object is object, call deepClone recursively, that is, copy a value object to the corresponding value of the new object. } else { result[key] = obj[key];//If the attribute value of the object is not object, directly copy each key value of the parameter object to the key-value pair corresponding to the new object. } } return result; } return obj; } let testArray = ["a", "b", "c", "d"]; let testRes = deepClone(testArray); console.log(testRes); console.log(typeof testRes[1]); let testObj = { name: "weiqiujuan", sex: "girl", age: 22, favorite: "play", family: {brother: "son", mother: "haha", father: "heihei"} }; let testRes2 = deepClone(testObj); testRes2.family.brother = "weibo"; console.log(testRes2);
3. Use the “Array.prototype.forEach” method of the array to copy to realize deep copy.
let deepClOne= function (obj) { let copy = Object.create(Object.getPrototypeOf(obj)); let propNames = Object. getOwnPropertyNames(obj); propNames. forEach(function (items) { let item = Object. getOwnPropertyDescriptor(obj, items); Object.defineProperty(copy, items, item); }); return copy; }; let testObj = { name: "weiqiujuan", sex: "girl", age: 22, favorite: "play", family: {brother: "wei", mother: "haha", father: "heihei"} } let testRes2 = deepClone(testObj); console.log(testRes2);
Recommended tutorial: “JS Tutorial”
The above are the details of the three implementation methods of JS deep copy, please pay attention to other related articles on 1024programmer.com!