First figure out a few concepts:
I. Specific data types are divided into two categories:
1. Original data type
2. Reference data types
The original data type stores the actual address of the object, including:
Number, String, Boolean, and two special null, undefined
The reference data type is where the object's reference address is stored, including:.
Array, function, object
Two. Shallow cloning:
The original type is a value pass, and the object type is still referenced, which means that the object type clones the reference address, and the reference address points to the same data space.
When the cloned data is changed, the cloned data also changes because the reference object is the same, so the data is the same, and the original data is affected when the new object is changed.
Three. Deep cloning:
All elements or attributes are completely copied, completely detached from the original object, meaning that all modifications to the new object are not reflected in the original object.
See the following code specifically:
var a = 1; var b = A; A = ten; Console.log (b); Console.log (a);//1,10 var a = ' Hello '; var b = A; A = ' world '; Console.log (b); Console.log (a);//Hello,world var a = true; var b = A; A = false; Console.log (b); Console.log (a);//True,false
These are meta data types, the cloned data is not related to the original data, the new data changes will not affect the original data.
Look at the following code:
var a = [0, 1, 2, 3]; var B = A; B.push (4); Console.log (a); [0, 1, 2, 3, 4]
B is a cloned object, [0,1,2,3] is an array, which belongs to the reference data type, so a stores the reference address of this array. b Shallow Clone A, so B and A is the same reference address, so the operation of B will also affect the original data.
The way to solve this problem is to use deep cloning:
function Clone (obj) { var buf; if (obj instanceof Array) { buf = []; var i = obj.length; while (i--) { Buf[i] = Clone (Obj[i]); } return buf; } else if (obj instanceof Object) { buf = {}; For (var k in obj) { Buf[k] = Clone (Obj[k]); } return buf; } else{ return obj; } }
The more concise wording is as follows:
function Clone (obj) { var o = obj instanceof Array? [] : {}; For (var k in obj) o[k] = typeof obj[k] = = = Object Clone (Obj[k]): obj[k]; return o;} var a = [[1, 2, 3], [4, 5, 6, 7]];var B = Clone (a); Console.log (b);
In the normal development, I generally use json.parse (json.stringify (obj));
But there's a problem with this approach, like
var a={' A ': function () {}, "B": 111, "C": undefined}
var b=json.parse (Json.stringify (a));
Console.log (b);//{b:111}
This means that filtering out the value is the property of function undefine, which needs attention when used.
JS Shallow clone/Deep clone