Sometimes, we need to replicate an object, such as the following requirements:
1. Using recursion to implement a deep clone, you can copy a target object and return a full copy
2. The copied object type is limited to numbers, strings, booleans, dates, arrays, object objects.
<script> function isobject(obj){ if(Object. Prototype.toString.call (obj) = = =' [Object Array] '||Object. Prototype.toString.call (obj) = = =' [Object Object] ')return true;Else return false; } function cloneobject(obj){ varCloneobj; cloneobj= (objinstanceof Array) ? []:{};//Determine object type, new Clone object for(varIinchobj) {if(Obj.hasownproperty (i)) {Cloneobj[i]=isobject (obj[i])? Cloneobject (Obj[i]): Obj[i]; } }returnCloneobj; }</script>
In the topic, object objects contain two types, one array and the other {}
Obj instanceof Array determines which of the new cloned objects belong to
For simple arrays, we will encounter this situation
var ary=[1,2,3,4];var ary1=ary;ary[0]=8;console.log(ary[0]);//结果为8console.log(ary1[1]);//结果为8
Why does this happen?
Arrays are reference type data, when assignments are made between arrays, no additional memory space is created for the new array, but instead the reference address of the new array variable is pointed to the original array, so the new array changes as the original array changes.
This is not the result we want, so we need to consider array cloning.
Let's add an array clone to the arrays array prototype
There are many ways to implement array cloning, simply enumerate several:
1. One of the easiest ways we can think of
Array.prototype.clone=function(){ var a=[]; for(var i=0,l=this.length;i<l;i++) a.push(this[i]); return
2. Slice method through the Array object
The slice method returns a segment of the array by passing the value of the parameter start and end, which does not operate on the original array. We can make it return all items by slice (0).
Array.prototype.clone=function(){ returnthis.slice(0
3. Concat method through the Array object
The Concat method is used to implement merging of arrays. By merging with an empty function, we can implement our cloning function.
Array.prototype.clone=function(){ return [].concat(this//或者 Array.prototype.clone=function(){ returnthis
Deep Clone objects