Home > Article > Web Front-end > Introduction to the difference between deep copy and shallow copy in JavaScript
This article brings you an introduction to the difference between deep copy and shallow copy in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
This article explains the difference between deep copy and shallow copy in JavaScript.
Shallow Copy/Shallow Copy
Shallow copy refers to copying the reference value.
var original = {"prop1" : "Prop1", "prop2" : "prop2"}; console.log(JSON.stringify(original)); // {"prop1" : "Prop1", "prop2" : "prop2"} var shallowCopy = original; console.log(JSON.stringify(shallowCopy)); // {"prop1" : "Prop1", "prop2" : "prop2"} shallowCopy.prop1 = "ChangedProp1"; console.log(JSON.stringify(original)); // {"prop1" : "ChangedProp1", "prop2" : "prop2"} console.log(JSON.stringify(shallowCopy)); // {"prop1" : "ChangedProp1", "prop2" : "prop2"}
https://smoothprogramming.com...
Note:
In a shallow copy, the original value and the copy share the same attributes.
Shallow copy only copies the object reference.
In shallow copy, if the copied object is modified, it will affect the original object, and vice versa.
In js, the assignment of arrays and objects defaults to shallow copy.
Deep Copy
Deep copy refers to recursively copying the properties of an object to a new object. In jquery we use $.extend to perform deep copy.
$.extend(deepCopy, target, object1, [objectN] )
The first parameter is passed in true, indicating that this is a deep copy, target is the target object, object1, the original object.
var original = {"prop1" : "Prop1", "prop2" : "prop2"}; console.log(JSON.stringify(original)); // {"prop1" : "Prop1", "prop2" : "prop2"} var deepCopy = $.extend(true, {}, original); console.log(JSON.stringify(deepCopy)); // {"prop1" : "Prop1", "prop2" : "prop2"} deepCopy.prop1 = "ChangedProp1"; console.log(JSON.stringify(original)); // {"prop1" : "Prop1", "prop2" : "prop2"} console.log(JSON.stringify(deepCopy)); // {"prop1" : "ChangedProp1", "prop2" : "prop2"}
https://smoothprogramming.com...
The above is the detailed content of Introduction to the difference between deep copy and shallow copy in JavaScript. For more information, please follow other related articles on the PHP Chinese website!