深拷贝与浅拷贝
1、基本数据类型的拷贝就是值得拷贝
2、引用数据类型的拷贝分为浅拷贝跟深拷贝
浅拷贝:目标对象跟源对象共用一个实体,只是变量名不同
深拷贝:目标对象跟源对象都是独立的个体
3、浅拷贝的方法:Object.assign()
4、深拷贝的方法:
4-1:将对象转换成字符串(JSON.stringfy)->再将字符串转换成对象(JSON.parse)
注意:无法拷贝原始对象的函数,因为函数无法转换成字符串
4-2:递归循环
function deepCopy(origin,target){ var target = null; if(typeof origin === 'object' && origin !== null){ target = origin instanceof Array ? [] : {} for(var key in origin){ target[key] = deepCopy(origin[key],target[key]); } }else{ target = origin; } return target } //例子 var obj = { "request_id": "9cf24cde471257bdff47-0000", "code": 0, "data": [ { "id": "1", "parent_id": "0", "name": "佛山分公司", "children": [ { "id": "2", "parent_id": "1", "name": "总经办", "children": [ ] }, { "id": "5", "parent_id": "1", "name": "综合管理部", "children": [ { "id": "8", "parent_id": "5", "name": "行政部", "children": [ ] }, { "id": "9", "parent_id": "5", "name": "人事部", "children": [ ] } ] } ] } ], } var target = null; target = deepCopy(obj,target) console.log('111',target);