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