Home >Web Front-end >JS Tutorial >Three implementation methods of JS deep copy
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Three implementation methods of JS deep copy
1. Convert the object into JSON string form, and then convert it into a native JS object;
//_tmp和result是相互独立的,没有任何联系,有各自的存储空间。 let deepClone = function (obj) { let _tmp = JSON.stringify(obj);//将对象转换为json字符串形式 let result = JSON.parse(_tmp);//将转换而来的字符串转换为原生js对象 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 implement traversal and copying;
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]);//如果对象的属性值为object的时候,递归调用deepClone,即在吧某个值对象复制一份到新的对象的对应值中。 } else { result[key] = obj[key];//如果对象的属性值不为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 achieve 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 is the detailed content of Three implementation methods of JS deep copy. For more information, please follow other related articles on the PHP Chinese website!