Detailed explanation principle of deep and shallow cloning of JavaScript array and non array objects

  • 2021-11-29 06:01:34
  • OfStack

What is shallow cloning, deep cloning 1. Cloning array 1.1 shallow cloning 1.2 deep cloning 2. Cloning non-array objects 2.1 shallow cloning 2.2 deep cloning 3. Integrating deep cloning functions

What are shallow cloning and deep cloning

Shallow cloning: The value stored in the stack is directly assigned to the corresponding variable, if it is a basic data type, the corresponding value is directly assigned, and if it is a reference type, the address is assigned.
Deep cloning: Assign the data to the corresponding variable, thus generating a new data irrelevant to the source data (the data address has changed). That is, attributes at all levels of objects.
In JavaScript, the basic data type can be cloned by using the symbol "=", while the reference data type only changes the direction of variables, but does not really clone.

1. Cloning an array

1.1 Shallow cloning

The for loop was used for shallow cloning.


var arr1 = ['demo', 1, 2];
var arr2 = [];
//  Shallow cloning of arrays 
for (var i = 0; i < arr1.length; i++) {
    arr2[i] = arr1[i];
}
console.log(arr2);
console.log(arr1 == arr2);

Output:

Array(3)0: "demo"1: 12: 2length: 3[[Prototype]]: Array(0)
false

1.2 Deep cloning

Deep cloning using recursion.


function deepClone(o) {
	var result = [];
	for (var i = 0; i < o.length; i++) {
		result.push(deepClone(o[i]));
	}
	return result;
}

2. Cloning non-array objects

2.1 Shallow cloning

The for loop was used for shallow cloning.


var obj1 = { a: 1, b: 2, c: 3, d: [4, 5, { e: 'demo' }] };
var obj2 = {};
//  Shallow cloning of objects 
for (var i in obj1) {
    obj2[i] = obj1[i];
}
console.log(obj2);
console.log(obj1 == obj2);

Output:

{a: 1, b: 2, c: 3, d: Array(3)}
false

2.2 Deep cloning

Deep cloning using recursion.


function deepClone(o) {
	var result = {};
	for (var i in o) {
		result[i] = deepClone(o[i]);
	}
	return result;
}

3. Integrate deep cloning functions


var obj1 = { a: 1, b: 2, c: 3, d: [4, 5, { e: 'demo' }] };
var arr1 = ['demo', 1, 2];
//  Deep cloning 
function deepClone(o) {
    if (Array.isArray(o)) {
        //  Is an array 
        var result = [];
        for (var i = 0; i < o.length; i++) {
            result.push(deepClone(o[i]));
        }
    } else if (typeof o == 'object') {
        //  Not an array, but an object 
        var result = {};
        for (var i in o) {
            result[i] = deepClone(o[i]);
        }
    } else {
        //  Basic type value 
        var result = o;
    }
    return result;
}
console.log(deepClone(arr1));
console.log(deepClone(obj1));

Related articles: