1.手写深拷贝
function deepCopy(target,source) {
//1.遍历对象拿到每一个属性
for (let key in source){
if (source.hasOwnProperty(key)){//必须写这一步
//2.拿到每个属性的值
let sourceValue = source[key];
if (sourceValue instanceof Object){//如果当前属性值是引用类型
let subTarget = new sourceValue.constructor();
target[key] = subTarget;//将new的引用类型添加到target上
deepCopy(subTarget,sourceValue);
} else{
target[key] = source[key];
}
}
}
}
2.JSON.stringify和JSON.parse
function deepcopy(obj) {
return JSON.parse(JSON.stringify(obj));
}
缺陷:对于undefined和Symbol类型的数据会被忽略,function也会被忽略
3.jQuery的extend方法实现深拷贝,会忽略undefined类型
let symbol = Symbol('id');
let obj = {
name:'andy',
age:21,
friends:['Tom','Peter','Ted'],
un:undefined,
sy:symbol,
fn:function () {
console.log('test');
}
};
let newObj = {};
$.extend(true,newObj,obj);//true代表深拷贝
console.log(obj);
console.log(newObj);//没有un属性,被过滤掉了