先定义一个对象
var obj1 = {
name:"bgg",
age:12,
skill:function(){
console.log("333")
},
arr:["1","2","3"]
}
一、浅拷贝
var obj2 = obj1;
obj2.name = "奥巴马"
console.log("浅拷贝2:",obj2);//浅拷贝2: {name: "奥巴马", age: 12, skill: ƒ, arr: Array(3)}
console.log("浅拷贝1:",obj1);//浅拷贝1: {name: "奥巴马", age: 12, skill: ƒ, arr: Array(3)}
结果:原对象和拷贝后的对象都被修改了!
二、深拷贝
//用递归函数
function deepCopy(obj,newObj){
for(var i in obj){
if(typeof obj[i] == "object"){//数组和函数的typeof都是object
newObj[i] = Array.isArray(obj[i])?[]:{};//判断类型 是数组or对象
deepCopy(obj[i],newObj[i]);//递归
}else{
newObj[i] = obj[i];
}
}
return newObj;
}
var newObj = {};//根据定义的递归函数,必须先声明个对象
var res = deepCopy(obj1,newObj);//调用函数
console.log("深拷贝原对象:",res)//深拷贝原对象:{name: "奥巴马", age: 12, skill: ƒ, arr: Array(3)}
//修改方法:
res.skill = function(){
console.log("99999")
};
obj1.skill();//333
res.skill();//99999
//修改数组
res.arr[0] = "888";
console.log(obj1.arr);// ["1", "2", "3"]
console.log(newObj.arr);// ["888", "2", "3"]
结果:拷贝后的原对象没有被修改,而深拷贝出来的对象成功可修改!
网友评论