clone of an object

Shallow clone

Let object obj1 clone object obj

var obj = {
	
name : 'Mo Xiaobai',
	
age : '16',
	
son : 'Mo Yan Qiuyu'
	
}

var obj1 = {};

function clone(origin,target) {
	
for (var prop in origin) {
	
target[prop] = origin[prop];
	
  }

}

clone(obj, obj1);

Use for..in to extract each attribute value of the obj object and assign it to the object obj1, which completes the clone.


Regarding the above clone, in order to prevent the user from not passing the formal parameters or actual parameters of the target, he wants to save the cloned result as an object.

Without further ado, look at the code:

var obj = {
	
name : 'Mo Xiaobai',
	
age : '16',
	
son : 'Mo Yan Qiuyu'
	
}
	
var obj1 = {};

function clone(origin,target) {
	
var target = target || {};
	
for (var prop in origin) {
	
target[prop] = origin[prop];
	
  }

return target; //must return outside the for..in loop

}

var demo = clone (obj)

clone(obj,obj1);

If the user normally passes parameters and wants to clone obj1 into obj,

var target = target || {};And return target;these two lines of code are of little use to prevent errors.

But when the user wants to take out the cloned object, they use these two strings of codes, and finally return the object to the force demo. In fact, these two strings of codes are spare.


deep clone

That's the point of this class

When cloning an object, if the reference value is cloned,

If the target object or the original object modifies the reference value, the reference value in the target object or the original object will also be modified

After cloning, no matter what is modified, it will not affect each other.


Operation ideas:

1. Determine whether it is the original value

1.1 The method to use: typeof.

1.2 If the return value is object, it is a reference value.

1.3 Then determine whether the reference value is an object or an array, three methods  . It is recommended to use toSring.

1.4 If it is an object, add an object, and if it is an array, add an array.

If typeof returns something other than object , just perform a shallow clone directly.

2. Use recursive loops.

3. Perfect.

// Deep clone an object, deepClon (original object, target object), you can also take a variable to receive an object, origin is a required object
	function deepClone(origin,target){
		
		var target = target || {};
		
		for (var prop in origin) {
			
			if(typeof origin[prop] == "object") {
				
				if(Object.prototype.toString.call(origin[prop]) == "[object Array]"){
					
					target[prop] = [];
					
				}else{
					
					target[prop] = {};
					
				}
				
				deepClone(origin[prop],target[prop]);
				
			}else{
				
				target[prop] = origin[prop];
				
			}
			
		}
		return target;
	}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326045155&siteId=291194637