浅拷贝----------------------------------------------------------------------
深拷贝--------------------------------------------------
let obj1 = {
age: 10,
sex: "男",
car: ["奔驰", "宝马", "特斯拉", "奥拓"],
dog: {
name: "大黄",
age: 5,
color: "黑白色"
}
};
let obj2 = {};//空对象
//通过函数实现,把对象a中的所有的数据深拷贝到对象b中
// use recursion
function deepCopy(obj,targetObj){
for (let key in obj){
let item = obj[key];
if (item instanceof Array){//if array
targetObj[key] = [];
deepCopy(item,targetObj[key]);
}else if (item instanceof Object){//if object
targetObj[key] = {};
deepCopy(item,targetObj[key]);
}else {//normal attribute
targetObj[key] = obj[key];
}
}
}
deepCopy(obj1,obj2);
兼容低版本浏览器----------------------------------------------------
a = [2,3];
b = {i:3}
c = function () {
aaa = 1;
}
function deepCopy(a) {
let obj;
if(Object.prototype.toString.call(a) === '[object Array]') {
obj = []
for (let i = 0; i < a.length; i++) {
obj.push(deepCopy(a[i]));
}
} else if(Object.prototype.toString.call(a) === '[object Object]') {
obj = {}
for (let i in a) {
obj[i] = deepCopy(a[i]);
}
} else {
return a;
}
return obj;
}
console.log(deepCopy(c))