Deep and shallow copy (js/jQuery)

Deep copy is a problem that occurs during the copying of reference data types (array objects).

Shallow copy of JS


Direct copying copies the memory address of the array/object, which is essentially a reference data type. All variables store the same memory address and operate the same storage space. The operation of any variable will affect other variables. . As follows:

const arr1 = ['北京', '上海', '广州', '深圳', '武汉'];

const arr2 = arr1;

console.log(arr1);
console.log(arr2);

The variable arr1 stores the memory address of the array, and the shallow copy is to assign the memory address of the array stored in the variable arr1 to the variable arr2 for storage, that is, the variable arr2 and the variable arr1 store the same memory address, and operate through one of the variables Array, another variable is also affected, change Beijing in arr1 to Tianjin, then Beijing in arr2 will also become Tianjin.

JS deep copy


What is copied is the numerical data stored in the array/object. In essence, after several deep copies are executed, there are several independent reference data types, which store different memory addresses and operate in different storage spaces. A variable operates reference data Type has no effect on other variables, as follows:

const arr1 = ['北京', '上海', '广州', '深圳', '武汉'];
//创建一个新的引用数据类型
const arr3 = [];
//循环遍历arr1将arr1中的存储获取之后,存储到arr3中
arr1.forEach(item => {
   arr3.push( item );
})

arr3 is a new memory address, but the stored data value is the same as arr1, and the operation of arr1 is the storage space corresponding to the memory address of arr1, which has nothing to do with the storage space of arr3 and has no effect. Shanghai in arr1 is changed to Chengdu, and the value in arr3 does not change. Therefore, if you modify the data in arr3, there is no change in arr1.

jQuery deep and shallow copy


The deep and shallow copy in jQuery is special

1. There is no function of encapsulating shallow copy in the traditional sense in jQuery

2. $.extend() encapsulated in jQuery executes deep copy in the traditional sense by default

3. The so-called deep and shallow copy in jQuery refers to deep copy of one-dimensional data and shallow copy of two-dimensional data

4. The grammatical form of deep and shallow copy in jQuery

const 变量 = 数组/对象;

$.extend(变量 , 原始数组/对象);
//浅拷贝,一维数据 深拷贝,多维数据  浅拷贝


$.extend(true, 变量, 原始数组/对象);
//深拷贝,一维数据 多维数据 都是深拷贝

As follows:

//原始数组
const arr1 = ['北京' , '上海' , '广州' , '深圳' , '武汉' , [100,200,300,400] , {name:'王昭没有君啊' , age:22 , sex:'男'} ];

//jQuery的浅拷贝

//创建一个arr2
const arr2 = [];

//将arr1中的数据按照jQuery的浅拷贝语法复制到arr2中
//执行的是jQuery的浅拷贝
$.extend( arr2 , arr1 );

//创建一个arr2
const arr3 = [];

//将arr1中的数据按照jQuery的深拷贝语法复制到arr3中
//执行的是jQuery的深拷贝
$.extend(true, arr3, arr1);

Guess you like

Origin blog.csdn.net/weixin_58448088/article/details/123043479