Reference data type shallow copy and deep copy distinction

Hello everyone, I am here today to talk about our differences in shades of copies of a reference type.

Shallow copy
direct assignment memory address assignment, the same content after the assignment of the two variables, two variables are stored in the same memory address, an operation to another will change.
arr1 is stored in a variable address memory array
var arr1 = [1,2,3,4,5];

The memory address arr1 stored, assigned to arr2 is, two variables are stored in the same memory address
var arr2 = arr1;

arr1 operation, array, arr2 is also changed
because arr1 and arr2 is, while storing the same data, the same operation is also an array
Similarly, arr2 is, an operation array, will change arr1
arr1 [0] = 'Beijing';

console.log (arr2);
The output is Beijing, 2,3,4,5
deep copy
loop through, to obtain a reference data type, data stored in each assigned to a new variable, after the assignment of two variables, no any relationship.
var arr3 = [ 'Beijing', 'Shanghai', 'Guangzhou', 'Chongqing', 'Tianjin'];

Loop through, to get all the data values in arr3, assigned to the new array
var arr4 = [];

Through the loop, the index generating ARR3 all subscripts
for (var I = 0; I <=. 1-arr3.length; I ++) {
ARR3 [I] is to obtain data stored in the ARR3
arr4.push () in the ARR3 data arr3 [i], written into the arr4
arr4.push (ARR3 [I]);
}

console.log(arr4);

arr3 [0] = 'Wuhan';

console.log (arr3, arr4);
output is: arr3: Wuhan, Shanghai, Guangzhou, Chongqing, Tianjin.
arr4: Beijing, Shanghai, Guangzhou, Chongqing, Tianjin.

 

Guess you like

Origin www.cnblogs.com/rpxx/p/12549163.html