First, understand the meaning of shallow copy:
A shallow copy is simply a copy of an assignment, so why is it a shallow copy? Is because of the way the assignment will only the surface of the object is assigned to a new object, if there is a value as an array or object attribute, then it will only be copied to the property in the stack pointer address of the space, a new object of the attribute data will with a public the old object, that is to say two address pointing to the same data, a change will change.
Deep copy does not have the same problem. Reference the data type and it copies both the address and the data.
Deep copy will be implemented using methods:
1. Deep copy is implemented by recursive functions
for(let key in obj) {
if (obj[key] instanceof Array) {
newObj[key] = []
myCopy(newObj[key], obj[key])
} else if (obj[key] instanceof Object) {
newObj[key] = {}
myCopy(newObj[key], obj[key])
} else {
newObj[key] = obj[key]
}
}
}
Copy the code
2. Use JSON to implement deep copy
Parse (_obj) return newObj} let newObject = myCopy(obj)Copy the code
3. Use jQuery to implement deep copy
Copy the code