var obj={
id:1,
name:'andy',
age:18,
msg:{
sing:123
},
color:['pink','red']
};
var o={};
function deepCopy(newobj,oldobj) {
for(var k in oldobj){
if(oldobj[k] instanceof Array){
newobj[k]=[];
deepCopy(newobj[k],oldobj[k])
}
else if(oldobj[k] instanceof Object){
newobj[k]={};
deepCopy(newobj[k],oldobj[k])
}else{
newobj[k]=oldobj[k];
}
}
}
deepCopy(o,obj);
console.log(o);
Copy the code
Because arrays are objects. So check whether it’s an array first, and then check whether it’s an object.