Home > Web Front-end > JS Tutorial > body text

Let's learn about deep copy and shallow copy in JS

青灯夜游
Release: 2020-07-09 15:07:43
forward
2278 people have browsed it

Let's learn about deep copy and shallow copy in JS

Shallow copy

Shallow copy is a bit-by-bit copy of the object. Creates a new object that has an exact copy of the values ​​in the original object. If any field of the object is a reference to another object, only the reference address is copied, that is, the memory address is copied.

In plain language, shallow copy is a copy of the object address, and does not open a new stack. That is, the result of the copy is that two objects point to the same address. If you modify the attributes of one object, the other object will be copied. An object's properties can also change.

Deep copy

Deep copy copies all fields and copies the dynamically allocated memory pointed to by the fields. A deep copy occurs when an object and the objects it references are copied.

In plain language, deep copy opens up a new stack. Two objects correspond to two different addresses. Modifying the properties of one object will not change the properties of the other object.

Look See See Example

Shallow copy: It copies the reference of X to Y middle. Therefore, the addresses of X and Y are the same, which means they point to the same memory location.

Deep copy: Copy all members of X, allocate different memory locations for Y, and then assign the copied members to Y to implement Deep copy. In this way, if X disappears, Y is still valid in memory.

Consider the following code:

var employeeDetailsOriginal = {  
  name: '前端小智', 
  age: 18,
  Profession: '前端开发' 
};
Copy after login

Suppose you want to create a copy of this object, so that even if the original value is changed, the value of the original object can still be obtained through the copy.

I would do this:

var employeeDetailsDuplicate = employeeDetailsOriginal; // 浅拷贝
Copy after login

If we change a value:

employeeDetailsDuplicate.name = '王大治';
Copy after login

In this way, the properties of our original object employeeDetailsOriginal name will also change because this is a shallow copy. In this way, we will not be able to obtain the value of the original object. So this copying practice is wrong.

However, it is possible to create a deep copy by creating an entirely new variable using the properties of the original employeeDetailsOriginal variable.

var employeeDetailsDuplicate = {
  name: employeeDetailsOriginal.name,
  age: employeeDetailsOriginal.age, 
  Profession: employeeDetailsOriginal.Profession
}; // 深拷贝
Copy after login

Now, if you change employeeDetailsDuplicate.name, it will only affect employeeDetailsDuplicate and not employeeDetailsOriginal.

Lets learn about deep copy and shallow copy in JS

Talk about Object.assign()

Object.assign() is a method we often use. In fact, this method is shallow copy. But it has something special, that is, it can handle deep copies of the first layer.

var employeeDetailsOriginal = {  
  name: '前端小智',
  family: {
    name: '前端大家庭'
  }
};

var employeeDetailsDuplicate = Object.assign({}, employeeDetailsOriginal );

employeeDetailsDuplicate.name = '王大治'
employeeDetailsDuplicate.family.name = '后端大家庭'

console.log(employeeDetailsOriginal ); 
// { name: "前端小智", family: {name: "后端大家庭"} }
console.log(employeeDetailsDuplicate);
// { name: "王大冶智", family: {name: "后端大家庭"} }
Copy after login

Looking at the above example, the value of the attribute name has not changed, but the value of name in the attribute family has changed. .

How to implement deep copy

The only way is to clone this object.

对于简单的JSON对象,最简单的方法是

var objectIsNew  = JSON.parse(JSON.stringify(objectIsOld));

//如果使用jQuery,可以使用:

// 浅拷贝
var objectIsNew = jQuery.extend({}, objectIsOld);

// 深拷贝
var objectIsNew = jQuery.extend(true, {}, objectIsOld);
Copy after login

Pure JS method to deep copy objects (not the best method)

function keepCloning(objectpassed) {
  if (objectpassed=== null || typeof objectpassed!== 'object') {
    return objectpassed;
  }
  
  // 临时存储原始的obj的构造
  var temporary_storage = objectpassed.constructor(); 
  for (var key in objectpassed) {
    temporary_storage[key] = keepCloning(objectpassed[key]);
  }
   return temporary_storage;
}

var employeeDetailsOriginal = {  
  name: '前端小智', 
  age: 18, 
  Profession: '前端开发' 
};

var employeeDetailsDuplicate = (keepCloning(employeeDetailsOriginal));

employeeDetailsOriginal.name = "前端大治";

console.log(employeeDetailsOriginal);
console.log(employeeDetailsDuplicate);
Copy after login

Summary

Understand deep copy also Not only for answering interview questions, it is also very useful in actual development. For example, a bunch of data is returned in the background, and you need to perform operations on this bunch of data. However, in the case of multi-person development, you cannot know whether this bunch of data has other functions that need to be used. Direct modification may cause hidden problems. Copying can help you operate data more safely and securely. Use deep copy according to the actual situation, which is probably what it means.

This article is reproduced from: https://segmentfault.com/a/1190000020438346

Recommended related tutorials: JavaScript video tutorial

The above is the detailed content of Let's learn about deep copy and shallow copy in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template