Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Summary of deep and shallow copies of JavaScript objects

2025-04-07 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly introduces "the summary of deep copy and shallow copy of JavaScript object". In the daily operation, I believe that many people have doubts about the problem of deep copy and shallow copy summary of JavaScript object. The editor consulted all kinds of materials and sorted out simple and useful methods of operation. I hope it will be helpful to answer the doubts of "deep copy and shallow copy summary of JavaScript object". Next, please follow the editor to study!

What is a copy of an object?

Assigning one object to another is called a copy of the object.

What is a deep copy and what is a shallow copy?

Let's assume that object An is assigned to object B. Shallow copy means that modifying the properties and methods of B object will affect the properties and methods of An object. We call it shallow copy.

The following two cases are shallow copies:

1. By default, direct assignments between objects are shallow copies.

Let A = {

Name: 'zyx'

Age: 20

}

Let B = A

Console.log (B) / / {name: "zyx", age: 20}

/ / modify the name attribute of B

B.name = 'ls'

/ / An is also affected

Console.log (A) / / {name: "ls", age: 20}

Console.log (B) / / {name: "ls", age: 20}

Assignment operations (including objects as parameters, return values) do not open up new memory space, it just assigns a reference to the object. That is, in addition to the name B, there is no other memory overhead. Modifying An affects B, and modifying B also affects A.

2. If the properties of the object contain reference data types (arrays, objects), then even if it is not a direct assignment operation, but opens up a new layer of memory space, that is to say, only one layer of the An object is copied, which is still a shallow copy.

Let A = {

Name: 'ls'

Age: 20

Hobbies: ['dance','basketball','read']

Dogs: {

Name: 'rhubarb'

Color: 'yellow'

}

}

Let B = {}

/ / define a function that copies a copy of the properties of object A to B.

Function extend (obj1,obj2) {

For (var key in obj1) {

Obj2 [key] = obj1 [key]

}

}

Extend (A & M B)

/ / modify the reference type data in object B, and object An is also affected

B.dogs.color = 'red'

B.hobbies [0] = 'sing'

Console.log (B)

Console.log (A)

Modify the reference type data in object B, and object An is also affected and belongs to a shallow copy.

3. The new Object.assign () in ES6 is also a shallow copy of the object.

The Object.assign method is used for merging objects, copying all enumerable properties of the source object (source) to the target object (target). The first parameter of the Object.assign method is the target object, and the following parameters are the source object. Note that if the target object has an attribute with the same name as the source object, or if more than one source object has an attribute with the same name, the following properties override the previous properties.

Const obj1 = {a: {b: 1}}

Const obj2 = Object.assign ({}, obj1)

Obj1.a.b = 2

Obj2.a.b / / 2

In the above code, the value of the a property of the source object obj1 is an object, and the Object.assign copy gets a reference to that object. Any changes to this object will be reflected on the target object.

4. Extension operator (.)

The extension operator can be used to clone or copy attributes when constructing literal objects, which belongs to shallow copy.

Var obj = {avell _ 1} _ b: {CRAV _ 1}}

Var obj2 = {... obj}

Obj.a=2

Console.log (obj); / / {aVO2Jing b: {CRAV 1}}

Console.log (obj2); / / {avell 1legine b: {CRAV 1}}

Obj.b.c = 2

Console.log (obj); / / {aVO2Jing b: {CRAV 2}}

Console.log (obj2); / / {avell 1legine b: {CRAV 2}}

5. Array.prototype.slice ()

The slice () method returns a new array object, which is a shallow copy of the original array determined by begin and end (excluding end). The original array will not be changed.

Deep copy means that modifying the properties and methods of object B will not affect the properties and methods of object A, which we call deep copy.

The following two cases are deep copies:

5.1. By default, if the attribute of an object is a basic data type, then copying (copying) is a deep copy.

If the attributes of object An are basic data types (Number, String, etc.), what should you do if you want to make a deep copy of A to B? when the object A to be copied has only basic type data, you only need to open up a space to store B in memory.

Let A = {

Name: 'zyx'

Age: 20

}

Let B = {}

/ / define a function that copies a copy of the properties of object A to B.

Function extend (obj1,obj2) {

For (var key in obj1) {

Obj2 [key] = obj1 [key]

}

}

Extend (A & M B)

Console.log (B) / / {name: "zyx", age: 20}

B.name = 'ls'

Console.log (B) / / {name: "ls", age: 20}

Console.log (A) / / {name: "zyx", age: 20}

In this way, deep copy is achieved.

5.2. If the object to be copied also contains reference data types, that is, the object also contains arrays or objects, in the case of layers of nesting, if you want to achieve a deep copy of the object, you can use a recursive way to make a deep copy.

Let A = {

Name: 'ls'

Age: 20

Hobbies: ['dance','basketball','read']

Dogs: {

Name: 'rhubarb'

Color: 'yellow'

}

}

Let B = {}

/ / define a function that copies a copy of the properties of object A to B.

Function extend (obj1,obj2) {

For (var key in obj1) {

Var item = obj1 [key]

If (item instanceof Array) {

Obj2 [key] = []

Extend (item,obj2 [key])

} else if (item instanceof Object) {

Obj2 [key] = {}

Extend (item,obj2 [key])

} else {

Obj2 [key] = item

}

}

}

Extend (A & M B)

B.dogs.color = 'red'

B.hobbies [0] = 'sing'

Console.log (B)

Console.log (A)

Run found that modifying the reference data type of the B object will not affect the An object and complete the deep copy.

We can encapsulate and optimize the deep-copied code.

Function deepClone (obj) {

Let cloneObj = {}

For (let key in obj) {

If (typeof obj [key] = 'object') {

CloneObj [key] = deepClone (obj [key])

} else {

CloneObj [key] = obj [key]

}

}

Return cloneObj

}

5.3. deep copy through JSON.stringify.

JSON.stringify () is the most commonly used deep copy method in the front-end development process, the principle is to serialize an object into a JSON string, convert the content of the object into a string form and save it on disk, and then use JSON.parse () deserialization to turn the JSON string into a new object.

Var obj1 = {

A:1

B: [1,2,3]

}

Var str = JSON.stringify (obj1)

Var obj2 = JSON.parse (str)

Console.log (obj2); / / {aVera 1pr b: [1m 2je 3]}

Obj1.a=2

Obj1.b.push (4)

Console.log (obj1); / / {aVera 2meme b: [1dje 2je 3je 4]}

Console.log (obj2); / / {aVera 1pr b: [1m 2je 3]}

At this point, the study on "the summary of deep and shallow copies of JavaScript objects" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report