Javascript object copy reference mechanism and $.extend copy characteristics

First review the variable types in javascript

basic type

  • number
  • string
  • boolean
  • undefined
  • null

reference type

  • function
  • array
  • date
  • Regular
  • mistake

The copy of the basic type variable, after the content is modified, will not affect another variable

var a = 1;

var b =a;

a = 2;

console.log(a);//2

console.log(b);//1

If the reference type variable assigns the content of the A object to the B object, the B object is only a reference to the A object. If the content of B is modified at this time, the content of A will also change accordingly.

var a = {a:1,b:2};

var b = a;

b.b = 3;

console.log(a);//{a:1,b:3}

console.log(b);//{a:1,b:3}

From this conclusion, under Javascript, assigning an object type variable only gets a reference to the object.

However, in some cases, due to functional requirements, it is necessary to require variables to modify their contents after obtaining a copy of another object without affecting each other; using Javascript natively, you can refer to the following methods:

var arr = {"a":"1","b":"2"};

var arr1 = arr;

arr = {};

arr["a"] = 2;

console.log(arr);//{"a":2}

console.log(arr1);//{"a":"1","b":"2"}

The principle is that when the A variable is a reference to the B object variable, leave A blank, and then set the content for A, it will no longer be a reference to B

 

You can also use the JSON.stringify method and jQuery's $.parseJSON method for processing (slightly troublesome)

var data = {a:1,b:2,c:3,d:[0,1,2,3]};

var str = JSON.stringify(data);

var data1 = $.parseJSON(str);

data1["e"] = 5;

data1["d"][0] = 22;

console.log(data);//{a: 1, b: 2, c: 3, d: [0,1,2,3]}

console.log(data1);//{a: 1, b: 2, c: 3, d: [22,1,2,3], e: 5}

This conversion process is actually to regenerate the object.

 

Use jQuery's $.extend() method to extend and copy objects

var a = {a:1,b:2};

var b = $.extend({},a);

b.b = 3;

console.log(a);//{a:1,b:2}

console.log(b);//{a:1,b:3}

In the above method, if there are sub-objects in the properties of the A variable, such as: {a:1,b:2,c:{aa:11,bb:22}}, when copying, the content of the sub-objects is still The way of citing will affect each other

var a = {a:1,b:2,c:{aa:11,bb:22}};

var b = $.extend({},a);

b.b = 3;

b.c.aa = 33;

console.log(a);//{a:1,b:2,c:{aa:33,bb:22}}

console.log(b);//{a:1,b:3,c:{aa:33,bb:22}}

Using the deep copy method of the $.extend() method can eliminate the above problems. Using deep copy, even if there are multiple levels of child objects in the parent object, a complete copy will still be performed, and no object reference will be made.

var a = {a:1,b:2,c:{aa:11,bb:22}};

var b = $.extend(true,{},a);

b.b = 3;

b.c.aa = 33;

console.log(a);//{a:1,b:2,c:{aa:11,bb:22}}

console.log(b);//{a:1,b:3,c:{aa:33,bb:22}}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325443692&siteId=291194637