js中深拷贝的方法 JS深浅拷贝实现方法



文章插图
js中深拷贝的方法 JS深浅拷贝实现方法

文章插图
1、利用JSON对象字符串转换方法(对象中不能有函数,值不能是引用的) 。
function deepCopy(ele) {return JSON.parse(JSON.stringify(ele)); } const obj = {a: {b: [1, [2, [, 3, 4]], { c: 5 }],}, }; const newObj = deepCopy(obj);newObj.a.b[2].c = 6;console.log(newObj.a.b[2].c, obj.a.b[2].c); // 6 52、利用递归遍历的方法
【js中深拷贝的方法 JS深浅拷贝实现方法】function deepCopy(ele) {const type = typeof ele;const baseType = ["boolean","number","string","undefined","function",];if (baseType.indexOf(type) > -1 || ele === null) return ele;const newType = Object.prototype.toString.call(ele);if (newType === "[object Array]") {const len = ele.length;if (!len) return [];const res = [];for (let i in ele) {res.push(deepCopy(ele[i]));}return res;}if (newType === "[object Object]") {if (Object.keys(ele).length === 0) return {};const res = {};for (let key in ele) {res[key] = deepCopy(ele[key]);}return res;}} const obj = {a: {b: [1, [2, [, 3, 4]], { c: 5 }],}, };const newObj = deepCopy(obj);newObj.a.b[2].c = 6;console.log(newObj.a.b[2].c, obj.a.b[2].c); // 6 5