Home >Web Front-end >JS Tutorial >Let's learn about deep copy and shallow copy in JS

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

青灯夜游
青灯夜游forward
2020-07-09 15:07:432308browse

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: '前端开发' 
};

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; // 浅拷贝

If we change a value:

employeeDetailsDuplicate.name = '王大治';

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
}; // 深拷贝

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: "后端大家庭"} }

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);

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);

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete