javascript ---> object that implements the deep copy

Shallow vs. deep copy

  • Shallow copy: one copy only when the data type is the object (Object, Array), only the reference copy.
  • Deep Copy: Copy multilayer complex data types, reallocating memory space.

Two methods to achieve shallow copy

  • Use for ... inrealization
var obj = {
	name: 'marron',
	age: 18,
	msg: {
		sex: "1" 
	}
}
var o = {};
for(let k in obj) {
	o[k] = obj[k]
};
console.log(o);
  • Use es6 providedObject.assign
var obj = {
	name: 'marron',
	age: 18,
	msg: {
		sex: "1"
	}
}
var o = {};
Object.assign(o, obj);
console.log(o);

The above objects achieved by objassigning O. However, o attributes in sexoperation. Operation is quoted.
That change o.msg.sexattribute obj.msg.sexproperties will change.

o.msg.sex = 2;
console.log(obj.msg.sex);	//	2

Implement deep copy

Obviously the above is not the result we need.
The core idea is to open up the memory space of complex data types assignment.
Try to use a recursive copy, ideas are as follows:

  1. Use for...inassignment
  2. When the assignment is first determined whether the current attribute array a instanceof Array, if the array is an array according recursive manner.
  3. In determining whether the current attribute objecta instanceof Object
  4. The remaining considered simple data types can be assigned directly ...
const deepCopy = (newobj, oldobj)  => {
	for(let k in oldobj) {
		let item = oldobj[k];
		if(item instanceof Array) {
			newobj[k] = [];
			deepCopy(newobj[k], oldobj[k])
		} else if (item instanceof Object){
			newobj[k] = {};
			deepCopy(newobj[k], oldobj[k])
		} else {
			newobj[k] = item
		}
	}
}
  • test:
let obj = {
	id: 1,
	name: 'marron',
	msg: {
		age: 18
	}
}
let o = deepCopy(o, obj);
console.log(o);
o.msg.age = 20;
console.log(obj);

Here Insert Picture Description

Published 177 original articles · won praise 22 · views 20000 +

Guess you like

Origin blog.csdn.net/piano9425/article/details/104080597