Detailed Explanation of angularJS Deep Copy

  • 2021-08-05 08:58:56
  • OfStack

Before understanding angular deep copy, first look at the following code.


var a = 1;
var b = a;
b = 2;
console.log(a + " " + b);

Obviously, the output a has a value of 1 and b has a value of 2. Next, look at one more piece of code.


var a = [1,2,3,4];
var b = a;
b.push(5);
console.log(a + " " + b);

Obviously, the value of the output a is [1, 2, 3, 4, 5] and the value of b is [1, 2, 3, 4, 5]. Let's look at the next code.


var a = {
  name:"zhangsan",
  age:20
}
var b = a;
b.name = "lisi";
b.age = 30;
console.log(a + " " + b);

Obviously, the output values of a and b are both {name: "lisi", age: 30}. Why is this?

In JavaScript or other languages, there are two nouns: deep copy and shallow copy. In the first code, a and b are both basic data types, and the values are changed after copying each other's values. At this time, the value of a does not change with the value of b, which is called deep copy. When the data type is complex data type such as array or object, after copying to the array or object, the value of the array or object is changed, and the value of a also changes with the value of b, which is called shallow copy.

How to solve the problem of deep copy?

Array data type: Use the concat () method. b = a. concat (); If the value of b is changed at this time, the value of a will not change with the value of b.

Object data type: b. name = a. name; b. age = a. age; In this case, by changing the value of b, the value of a does not change with the value of b. However, this method needs to know what fields are inside the a object. Copying one by one is particularly troublesome.

Deep Copy of AngularJS

Students who use angular may have overlooked the encapsulated method of angularJS. angular. isString (), angular. isNumber (), angular. isArray (), angular. isFunction (), and so on. Among them, angular. copy () can solve the problem of deep copy. As follows:


var a = {
  name :"zhangsan",
  age : 20
}
var b = angular.copy(a);

At this time, by changing the value of b, the value of a will not change with the change of the value of b, thus solving the problem of deep copy.


Related articles: