Shallow vs. deep copy JS-
- What is the deep and shallow copy copy
- Common deep copy and shallow copy Examples
- Achieve shallow copy
- Done manually
- Own function implementation (target): Object.assign ()
- Own function implementation (array): Array.concat ()
- Own function implementation (array): Array.slice ()
- Deep copy implementation
What is the deep and shallow copy copy
Shallow copy
When the copy is a copy of the address of an object, if they copy the object is modified, the copy of the object will also change
example:
var a=[1,2,3];
var b=a;
a[0]=4;
console.log(b[0]); //输出4
Deep copy
When copying a copy object is a value, the value of the copy of the object is not changed with the copy of the object
example:
var a=1;
var b=a;
a=2;
console.log(b); //输出1
Common deep copy and shallow copy Examples
var obj={
a:1,
b:2,
c:{
d:3
}
};
var obj2={};
obj2['a']=obj['a']; //深拷贝
obj2['c']=obj['c']; //浅拷贝,传的是d的地址
Achieve shallow copy
There follows a obj, to put it another shallow copy of the object:
var obj={
a:1,
b:2,
c:{
d:3
}
};
Done manually
var obj2={};
for(var i in obj){
obj2[i]=obj[i];
}
console.log(obj2); //{a: 1, b: 2, c: Object}
Own function implementation (target): Object.assign ()
Copy of the object
var obj2={};
Object.assign(obj2,obj); //Object.assign(目标对象,源对象)
Or this form:
var obj2=Object.assign({},obj);
A copy of the array
Copying the array transducer as {} [] to:
var arr=[1,2,3];
var arr2=Object.assign([],arr);
Own function implementation (array): Array.concat ()
concat () function describes
concat () is used to connect a plurality of arrays, and returns a copy of the connector will not affect the original array
Connection elements
var arr=[1,2,3];
console(arr.concat(4,5)); //1,2,3,4,5
Two arrays connected
var arr=[1,2,3];
var arr2=[4,5];
console(arr.concat(arr2)); //1,2,3,4,5
Most group connection
var arr=[1,2,3];
var arr2=[4,5];
var arr3=[6,7];
console(arr.concat(arr2,arr3)); //1,2,3,4,5,6,7
Achieve shallow copy
var arr=[1,2,{a:3}];
var arr2=arr.concat(); //没参数表示仅拷贝自身
arr2[2].a=4;
console.log(arr[2].a); //输出4,同Object.assign()一样仅拷贝了引用对象的地址
Own function implementation (array): Array.slice ()
slice () function describes
Array.slice (start, end); taken array elements, start specify the start position (from 0, if the number of negative values of flashbacks), end the specified end position (province available)
Achieve shallow copy
var arr=[1,2,{a:3}];
var arr2=arr.slice(0);
console.log(arr===arr2); //false,===表示严格相等
Deep copy implementation
jQuery's extend () function to achieve
extend () Introduction
extend () used to achieve the basic idea of recursive copy
extend () function to the contents of one or more objects into the target objects
extend (whether the depth merging, the target object, the object 1 merged, merged objects 2 ...)
whether the depth is shallow copy merge, false, true when the deep copy
Implement deep copy
var arr=[1,2,{a:3}];
var arr2=$.extend(true,{},arr);
arr2[2].a=4;
console.log(arr[2].a); //输出3,未被arr2影响