This question always comes up in the interview, so it’s better to summarize and deepen your impression
1. How to distinguish
Deep copy and shallow copy, in simple terms, is assumed that B copies A, when changing A, B changes, if B also changes, it is A shallow copy; If B doesn’t change, it’s a deep copy.
Let's look at a shallow copy example:Copy the code
let a=[0.1.2.3.4];
let b=a;
console.log(a === b); //true
a[0] =1;
console.log(a,b); / / a = b = [1,1,2,3,4],1,2,3,4 [1]
Copy the code
Why is that? I didn’t change the b array, did I? Huh? ? ? ?I looked it up and found that it was related to data types, so let’s talk about data types
2. Basic versus complex (reference) data types
Common interview questions: What are the data types?
Now that we know the basics, let’s talk about the basics.
2.1 Basic types —— Variable names and values are stored in stack memory
2.2 Reference Types ——- The variable name is in stack memory, which provides a reference address to a value in heap memory
When I saw this, I suddenly understood. Since a and B refer to the same heap address above, I assign a value to a, and the value in B changes as well.
3. Implementation method
3.1 shallow copy
- Object.assign()
// Target object
const target = { a: 1 };
// The merged source object
const source1 = { b: 2 };
const source2 = { c: 3 };
// object.assign () takes the first argument to the target Object and the rest to the source Object.
Object.assign(target, source1, source2);
console.log(target) // {a:1, b:2, c:3}
Copy the code
Object.assign() copies only the source Object’s own properties (not inherited properties), but also non-enumerable properties (enumerable: false).
Note: If the target object has a property of the same name as the source object, or multiple source objects have a property of the same name, the later property overrides the previous property.
If you want to learn more about object.assign (), please check out Ruan Yifeng’s introduction to ES6.
3.2 deep copy
- Parse and Stringify JSON objects
function deepClone(obj) {
let _obj = JSON.stringify(obj),
objClone = JSON.parse(_obj);
return objClone
}
let a = [0.1[2.3].4],
b = deepClone(a);
a[0] = 1;
a[2] [0] = 1;
console.log(a, b);
Copy the code
As you can see, B is completely unaffected by A.
- jQuery.extend()
$.extend( [deep ] , target, object1 , [objectN ])
- Deep: indicates the deep copy. If the value is true, it indicates the deep copy. If the value is false, it indicates the shallow copy.
- Target: A target Object of type Object to which member attributes of other objects will be attached.
- Object1,objectN(Optional): The first and NTH objects of type Object to be merged.
let a=[0.1[2.3].4],
b=$.extend(true,[],a);
a[0] =1;
a[2] [0] =1;
console.log(a,b);
Copy the code
You can see the same effect as above, but you need to rely on the jQuery library
I am front-end xiao Meng new thin cool, if my article is helpful to you, please click a like 👍🏻 to support me ~