catalogue
- 1、 Shallow copy
- 1、Object.assign(target,source,source…)
- 2. Extension operator (spread)
- 2、 Deep copy
- 1. Use object serialization JSON Stringify() and JSON parse()
- 2. Use recursion to judge the object properties
1、 Shallow copy
1、Object.assign(target,source,source…)
a. Multiple object replication is supported
b. If the source and target attributes are the same, source will copy the target attributes
c. Target can only be an object
var obj = {a:1,b:2}
undefined
Object.assign({c:3},obj)
{c: 3, a: 1, b: 2}
obj
{a: 1, b: 2}
Compatibility writing method if (object. Assign) {// compatible} else {// incompatible}
2. Extension 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}
objs.a=10
10
objs
{a: 10, b: 2, c: 3}
obj
{a: 1, b: 2, c: 3}
2、 Deep copy
1. Use object serialization JSON Stringify() and JSON parse()
Note: this method is only valid if the original object contains a serializable value type and there is no circular reference. An example of a non serializable value type is the date object – JSON Parse can only parse it as a string, but cannot parse it back to its original date object, or the attribute value in the object is function
var obj = {a:1,b:[1,2,3],c:{e:3},bool:false}
undefined
var objs = JSON.parse(JSON.stringify(obj))
undefined
objs
{a: 1, b: Array(3), c: {…}, bool: false}
objs.bool = 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 the 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();
copy.setTime(obj.getTime());
return copy;
}
// Handle Array
if (obj instanceof Array) {
copy = [];
for (var i = 0, len = obj.length; i < len; i++) {
copy[i] = clone(obj[i]);
}
return copy;
}
// Handle Function
if (obj instanceof Function) {
copy = function() {
return obj.apply(this, arguments);
}
return copy;
}
// Handle Object
if (obj instanceof Object) {
copy = {};
for (var attr in obj) {
if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);
}
return copy;
}
throw new Error("Unable to copy obj as type isn't supported " + obj.constructor.name);
}
The above is the details of JS object replication (deep copy and shallow copy). For more information about JS, please pay attention to other relevant articles of developeppaer!