Home > Article > Web Front-end > What is the difference between deep copy and shallow copy in JS?
#What is the difference between deep copy and shallow copy in JS?
The difference between the two is whether the copied entity of an object is actually obtained, rather than a reference. Deep copy opens up a memory address in the computer for storing the copied object, while shallow copy only It points to the copied memory address. If the object in the original address is changed, the shallow copied object will also change accordingly.
Deep copy
The simplest method is
JSON.parse(JSON.stringify()) function deepCopy(o) { return JSON.parse(JSON.stringify(o)) } var c = { age: 1, name: undefined, sex: null, tel: /^1[34578]\d{9}$/, say: () => { console.log('hahha') } } // { age: 1, sex: null, tel: {} }
It should be noted that this copy method cannot copy some special files Properties (such as regular expressions, undefine, function)
Use recursion to copy all hierarchical properties
function deepCopyTwo(obj) { let objClone = Array.isArray(obj) ? [] : {}; if (obj && typeof obj == 'object') { for (const key in obj) { //判断obj子元素是否为对象,如果是,递归复制 if (obj[key] && typeof obj[key] === "object") { objClone[key] = deepCopyTwo(obj[key]); } else { //如果不是,简单复制 objClone[key] = obj[key]; } } } return objClone; }
Shallow copy
object.assign(target,source)
Object The .assign method only copies enumerable properties in the source object and the properties of the object itself
If a property in the target object has the same key, the property will be overwritten by the property in the source. Properties of later sources will similarly override earlier properties.
Object.assign will skip those whose value is [null] null is a JavaScript literal that represents null or an "empty" value. That is, no object value is present. It is one of the JavaScript primitive values. ") or undefined source object.
Recommended tutorial: "JS Tutorial"
##
The above is the detailed content of What is the difference between deep copy and shallow copy in JS?. For more information, please follow other related articles on the PHP Chinese website!