1.使用JSON.stringify,JSON.parse
该方法只能拷贝Object对象,而无法拷贝undefined,function,RegExp等。
function deepCopy1(obj) {
// 使用JSON.stringify,JSON.parse
let objString = JSON.stringify(obj);
return JSON.parse(objString);
}
const obj1 = {
name: 'tototoo',
age: 23,
hobbies: [1, 2, 3]
};
const obj2 = deepCopy1(obj1);
obj2.age = 22;
obj2.hobbies[0] = 0;
// obj1 { name: 'tototoo', age: 23, hobbies: [ 1, 2, 3 ] }
console.log("obj1", obj1);
// obj2 { name: 'tototoo', age: 22, hobbies: [ 0, 2, 3 ] }
console.log("obj2", obj2);
2.使用Object.assign(target, source)
该方法不能拷贝对象内部的对象,无法完成深拷贝。
function deepCopy2(obj) {
return Object.assign({}, obj);
}
const obj1 = {
name: 'tototoo',
age: 23,
hobbies: [1, 2, 3],
address: undefined,
pointer: null
};
const obj2 = deepCopy2(obj1);
obj2.age = 22;
obj2.hobbies[0] = 0;
obj2.address = 'beijing';
/*
obj1 { name: 'tototoo',
age: 23,
hobbies: [ 0, 2, 3 ],
address: undefined,
pointer: null }
*/
console.log("obj1", obj1);
/* obj2 { name: 'tototoo',
age: 22,
hobbies: [ 0, 2, 3 ],
address: 'beijing',
pointer: null }
*/
console.log("obj2", obj2);
3.使用递归的方式拷贝
function deepCopy3(obj) {
let result = null;
// 1.判断是对象类型还是普通数据类型,普通数据类型直接赋值
if (typeof obj === 'object') {
// 2.若是对象类型,进行细分:[],{},RegExp,null
// 2.1若是数组
if (Array.isArray(obj)) {
result = [];
for (let i = 0; i < obj.length; i++) {
// 递归判断一下若有对象,在进行深拷贝
result.push(deepCopy3(obj[i]));
}
} else if (obj.constructor === RegExp) {
result = obj;
} else if (obj === null) {
result = obj;
} else { //普通对象
result = {};
// 保留原来对象类型,即原型上的信息
if (obj.__proto__) {
result.__proto__ = obj.__proto__;
}
for (key in obj) {
result[key] = deepCopy3(obj[key]);
}
}
// RegExp,null可以直接赋值,[],{}需要递归
} else { // 普通数据类型或者函数
result = obj;
}
return result;
}
let obj = {
name: 'tt',
family: {
father: 'ff'
},
info: [1, 2, 3, 4],
age: 16,
fuc: function() {}
};
let obj_ = deepCopy3(obj);
obj_.family['father'] = 'Trump';
obj_.info.push(0);
/*
obj { name: 'tt',
family: { father: 'ff' },
info: [ 1, 2, 3, 4 ],
age: 16,
fuc: [Function: fuc] }
*/
console.log("obj", obj);
/*
obj_ { name: 'tt',
family: { father: 'Trump' },
info: [ 1, 2, 3, 4, 0 ],
age: 16,
fuc: [Function: fuc] }
*/
console.log("obj_", obj_);