1. Shallow copy creates a new object with an exact copy of the original object’s property values. If the property is a primitive type, it copies the value of the primitive type, and if the property is a reference type, it copies the memory address, so if one object changes the address, it affects the other object.
2. A deep copy is a complete copy of an object from the memory. A new area is created in the heap memory to store the new object, and modification of the new object does not affect the original object.
A shallow copy can only copy one layer of objects. If the objects are nested, it cannot copy them.
Shallow copy:
1.Object.assign()
Let’s look at a normal shallow copy using object. assign
var obj1 = {
a:1,
b:2,
c:{
d:3
}
}
var obj2 = {}
Object.assign(obj2,obj1)
obj2.a=11
obj2.c.d=33
console.log(obj1); -----> {a:1,b:2,c:{d:33}}}
console.log(obj2); -----> {a:11,b:2,c:{d:33}}
Copy the code
== Note == :
- It cannot copy an object’s inherited properties
- Cannot copy the non-enumerable properties of an object
- Properties of type Symbol can be copied
var obj1 = {
a:{
b:1
}
}
Object.defineProperty(obj1,'c',{
value: 3,
enumerable: false
})
var obj2 = {}
Object.assign(obj2,obj1)
console.log(obj1) ----> {a:{b:1},c:3}
console.log(obj2) ----> {a:{b:1}}
Copy the code
2. Extend operators
var obj1 = {a:{b:1}} var obj2 = {... obj1} let arr = [1, 2, 3]; let newArr = [...arr];Copy the code
3. Array. Slice () method
Var obj1 = [1,2,{d:3}] var obj2 = obj1.slice() obj2[2]. D = 4 console.log(obj1); ----> [ 1, 2, { d: 4 } ] console.log(obj2); ----> [ 1, 2, { d: 4 } ]Copy the code
4. Array. Concat () method
Var obj1 = [1,2,{d:3}] var obj2 = obj1.concat([]) obj2[2].d = 4 console.log(obj1); ----> [ 1, 2, { d: 4 } ] console.log(obj2); ----> [ 1, 2, { d: 4 } ]Copy the code
Write a shallow copy by hand
function shallowClone(target){ let newResult = Array.isArray(target) ? [] : {} if(typeof target === 'object'){ for(item in target){ newResult[item] = target[item] } return newResult }else{ return Target}} var obj1 = [1,2,{d:3}] var obj2 = shallowClone(obj1) obj2[2]. ----> [ 1, 2, { d: 4 } ] console.log(obj2); ----> [ 1, 2, { d: 4 } ]Copy the code
Deep copy
1. JSON. Parse (JSON. Stringty ())
Parse (json.stringify (target))} var obj1 = [1,2,{d:3}] var obj2 =deepCloneByJson(obj1) obj2[2].d = 4 console.log(obj1); console.log(obj2);Copy the code
Attention = = = =
- If the value of the copied object is function, undefined, or symbol, the key/value pair will disappear in the string serialized by json. stringify.
- Copy Date, it will become a string
- Unable to copy non-enumerable properties
- Unable to copy the object’s prototype chain
- Copy RegExp and it will be empty {}
- Objects with NaN, Infinity, or JSON serialization become NULL
- Cannot copy object cyclic application
2. Write a deep copy by hand
function isComplexTypeData(obj){ return (typeof obj === 'object') && obj! ==null } function deepClone(obj, hash = new WeakMap()){ if(obj.constructor === Date) return new Date(obj) if(obj.constructor === RegExp) return new If (hash. Has (obj)) return hash. Get (obj) let desc =. RegExp(obj) let desc = Object.getOwnPropertyDescriptors(obj); let cloneObj = Object.create(Object.getPrototypeOf(obj), desc); hash.set(obj, cloneObj); For (let item in reflet.ownKeys (cloneObj)){cloneObj[item] = isComplexTypeData(obj[item]) &&typeof! == 'function' ? deepClone(obj,hash) : obj[item] } return cloneObj; }Copy the code
The top is written code and the bottom is test code
Let obj = {num: 0, STR: ", Boolean: true, unf: undefined, nul: null, obj: {name: 'I am an object ', id: 1}, arr: [0, 1, 2], func: function () {console.log(' I am a function ')}, date: new date (0), reg: New RegExp('/ I am a re /ig'), [Symbol('1')]: 1,}; Object.defineproperty (obj, 'innumerable', {enumerable: false, value: 'unenumerable'}); obj = Object.create(obj, Object. GetOwnPropertyDescriptors (obj) obj. Loop = obj / / set loop into the attribute of a circular reference let cloneObj = deepClone (obj)/finished/copy, experiment cloneObj.arr.push(4) cloneObj.func() console.log('obj', obj) console.log('cloneObj', cloneObj)Copy the code