浅拷贝----------------------------------------------------------------------
let obj1 = {
age: 10,
sex: "男",
car: ["奔驰", "宝马", "特斯拉", "奥拓"]
};
//另一个对象
let obj2 = {};
//写一个函数,作用:把一个对象的属性复制到另一个对象中,浅拷贝
//把a对象中的所有的属性复制到对象b中
function shallowCopy(obj,targetObj){
for (let key in obj){
targetObj[key] = obj[key];
}
}
shallowCopy(obj1, obj2);
console.dir(obj2);//开始的时候这个对象是空对象
console.dir(obj1);//有属性
//change car attribute
obj1.car.push("奥迪");
//the car of obj2 change,too.for the point of the car in obj2 is same as the obj1
console.log(obj2.car);
深拷贝--------------------------------------------------
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))
原文:https://www.cnblogs.com/gxw123/p/13051010.html