Article directory
the case
let person = {
name: 'lhg',
sex: '男',
friends: {
name: '张三',
sex: '男'
}
}
let newPerson = person
newPerson.name = '前端的炮灰'
console.log(person);
console.log(newPerson);
Output result:
The output result here is the same as what we all think, modify the name attribute of newPerson, and change the value of the name attribute of person. This is actually very easy to explain, the two point to the same object.
shallow copy
Let's write a function
let person = {
name: 'lhg',
sex: '男',
friends: {
name: '张三',
sex: '男'
}
}
/**
* 浅拷贝
* @param {*} obj
* @returns
*/
function clone(obj) {
if (typeof obj !== 'object' || obj == null) {
console.log(1);
return obj
}
let result
if (obj instanceof Array) {
result = []
} else {
result = {
}
}
for (let key in obj) {
result[key] = obj[key]
}
return result
}
let newPerson = clone(person)
newPerson.name = '前端的炮灰'
console.log(person);
console.log(newPerson);
output result
Here we can see that the effect we want has appeared, but new problems have appeared.
We modify the original
newPerson.name = '前端的炮灰'
Instead modify the properties in the subproperties object
newPerson.friends.name = '前端的炮灰'
The result is
It can be seen that we only copied one layer, so we need to implement copying in a recursive form, that is, deep copying, in order to achieve complete copying.
deep copy
let person = {
name: 'lhg',
sex: '男',
friends: {
name: '张三',
sex: '男'
}
}
/**
* 深拷贝
* @param {*} obj
* @returns
*/
function clone(obj) {
if (typeof obj !== 'object' || obj == null) {
return obj
}
let result
if (obj instanceof Array) {
result = []
} else {
result = {
}
}
for (let key in obj) {
//递归处理,我们在这里可以进行处理,可以只拷贝obj上有的属性
//在这里就不这样写了
//if (obj.hasOwnProperty(key)) {
// result[key] = clone(obj[key])
//}
result[key] = clone(obj[key])
}
return result
}
let newPerson = clone(person)
newPerson.friends.name = '前端的炮灰'
console.log(person);
console.log(newPerson);
The result is
It can be seen that this time we have achieved the desired result
lodash(cloneDeep)
Lodash has implemented deep copy, we can directly import and call
lodash-cloneDeep
There are several other copy methods, you can go to have a look