JS中的浅拷贝、深拷贝(递归实现)
2020-01-06 本文已影响0人
David_Rao
浅拷贝
复杂数据类型的数据复制的是地址,修改会被“共享”
方式一,使用copyObj[key] = obj[key]
var obj = {name: 'David', age: 18, pets: ['阿猫', '阿狗']};
var copyObj = {};
for(var key in obj){
copyObj[key] = obj[key];
}
obj.name = '周杰伦';
obj.pets.push('小黑');
console.log(obj); // name:'周杰伦', age:18, pets:["阿猫", "阿狗", "小黑"]
console.log(copyObj); // name:'David', age:18, pets:["阿猫", "阿狗", "小黑"]
方式二,使用Object.assign()
var obj = {name: 'David', age: 18, pets: ['阿猫', '阿狗']};
var copyObj = {};
Object.assign(copyObj, obj, {address: '广州'});
obj.name = '周杰伦';
obj.pets.push('小黑');
console.log(obj); // name:'周杰伦', age:18, pets:["阿猫", "阿狗", "小黑"]
console.log(copyObj); // name:'David', age:18, address:'广州', pets:["阿猫", "阿狗", "小黑"]
深拷贝
复杂数据类型的数据复制到新的地址,修改不会被“共享”
var obj = {
name: 'David',
age: 18,
friends: ['小明', '小红', '小黑'],
bestFriend: {
name: '小黑',
age: 19,
address: '广州',
pets: [{name: '土豆'}, {name: '马铃薯'}]
},
birthday: new Date()
};
function deepCopy2NewObj(fromObj, toObj) {
for(var key in fromObj){
var fromValue = fromObj[key];
if(!isObj(fromValue)){
toObj[key] = fromValue;
}else{
var tempObj = new fromValue.__proto__.constructor;
deepCopy2NewObj(fromValue, tempObj); // 递归
toObj[key] = tempObj;
}
}
}
function isObj(obj) {
return obj instanceof Object;
}
function isArr(obj) {
return Array.isArray(obj);
// return Object.prototype.toString.call(obj) === '[object Array]'; // 方式2
}
var newObj = {};
deepCopy2NewObj(obj, newObj);
console.log(obj);
console.log(newObj);