1. Light copy
1、(target,source,source...)
a. Can support multiple object copying
b. If the source and target attributes are the same source will copy the target attributes.
c. Target can only be an Object object object
var obj = {a:1,b:2} undefined ({c:3},obj) {c: 3, a: 1, b: 2} obj {a: 1, b: 2} Compatibility writingif(){//compatible}else{//不compatible}
2. Expansion operator (spread)
Supports copying multiple objects to one object "
var obj1 = { foo: "foo" }; var obj2 = { bar: "bar" }; var copySpread = { ...obj1, ...obj2 }; // Object {foo: "foo", bar: "bar"} copySpread {foo: "foo", bar: "bar"} var obj = {a:1,b:2,c:3} var objs = {...obj} objs {a: 1, b: 2, c: 3} =10 10 objs {a: 10, b: 2, c: 3} obj {a: 1, b: 2, c: 3}
2. Deep copy
1. Use object serialization () and ()
Note: This method is only valid if the original object contains a serializable value type and does not have any circular references. An example of a non-serialized value type is a Date object - it can only be parsed into a string and cannot be parsed back to its original Date object or the property value in the object is function
var obj = {a:1,b:[1,2,3],c:{e:3},bool:false} undefined var objs = ((obj)) undefined objs {a: 1, b: Array(3), c: {…}, bool: false} = true true objs {a: 1, b: Array(3), c: {…}, bool: true} obj {a: 1, b: Array(3), c: {…}, bool: false}
2. Use recursion to judge object properties
function deepClone(obj) { var copy; // If obj is null, undefined or not an object, return obj directly // Handle the 3 simple types, and null or undefined if (null == obj || "object" != typeof obj) return obj; // Handle Date if (obj instanceof Date) { copy = new Date(); (()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (var i = 0, len = ; i < len; i++) { copy[i] = clone(obj[i]); } return copy; } // Handle Function if (obj instanceof Function) { copy = function() { return (this, arguments); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (var attr in obj) { if ((attr)) copy[attr] = clone(obj[attr]); } return copy; } throw new Error("Unable to copy obj as type isn't supported " + ); }
The above is the detailed content of JS object copy (deep copy and shallow copy). For more information about JS, please pay attention to my other related articles!