本来这块也算很熟悉了,就是在回顾下,做个笔记
第一种写法:
//使用递归的方式实现数组、对象的深拷贝
function deepClone1(obj) {
//判断拷贝的要进行深拷贝的是数组还是对象,是数组的话进行数组拷贝,对象的话进行对象拷贝
var objClone = Array.isArray(obj) ? [] : {};
//进行深拷贝的不能为空,并且是对象或者是
if (obj && typeof obj === "object") {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
if (obj[key] && typeof obj[key] === "object") {
objClone[key] = deepClone1(obj[key]);
} else {
objClone[key] = obj[key];
}
}
}
}
return objClone;
}
第二种写法:
function clone(obj) {
var objClone={};
for(var i in obj){
if(typeof obj[i]=="object"){
objClone[i]=clone(obj[i])
}else{
objClone[i]=obj[i]
}
}
return objClone;
}
//定义要拷贝的对象
var obj={
name:'zhangsan',
sex:'man',
age:16,
aaa:undefined,
like:{
one:'eat',
two:'sleep',
three:'drink'
},
arr:[123,12,124,548],
fun:function () {
var aa=1;
}
};
console.log(deepClone1(obj));
cobj=clone(obj)
console.log(cobj);