<script> //Is it the original value? //Judging whether it is an array or an object //Create the corresponding array or object var obj={ name:'Spicy chicken', sex:'male', card:['laobi','feiwu'], wife:{ name:'Retarded', son:{ name:'Colour pen' } } } var obj1={} function deepClone(Origin,Target){ var Target=Target ||{}, toStr = Object.prototype.toString, arrStr = '[object Array]'; for(var prop in Origin){ //The first step is to determine whether the object is the original value. if(Origin.hasOwnProperty(prop)){ if(typeof(Origin[prop])=='object'){ if(toStr.call(Origin[prop]) == arrStr){ Target[prop]=[]; }else{ Target[prop] = {}; } deepClone(Origin[prop],Target[prop]); } else{ Target[prop] = Origin[prop]; } } } } </script>
Deep clone
Note: To determine whether it is a prototype, first think of the method for in and hasProperty, and then use typeof (Origin [prop]) ='object'?
There are three ways to judge arrays and objects: constructor, toString call, instance of
In this case, toString. call (Origin [prop]='arrStr') is used to determine whether it is [object Array]?
Finally, the corresponding arrays and objects are created by callback deepClone() method.
Here's how to improve the code by using the trinomial operator, add the judgement method is not empty, and add the return value Target.
function deepClone(Origin,Target){ var Target=Target ||{}, toStr = Object.prototype.toString, arrStr = '[object Array]'; for(var prop in Origin){ //The first step is to determine whether the object is the original value. if(Origin.hasOwnProperty(prop)){ if(typeof(Origin[prop])=='object' && Origin[prop] !=='null'){ target[prop] = toStr.call(Origin[prop]) == arrStr ?[]: {}; deepClone(Origin[prop],Target[prop]); } else{ Target[prop] = Origin[prop]; } } } return Target; }
Shallow cloning
var obj3={ name:'abc', sex:'boy', height:178} var obj4={} function clone(Origin,Target){ var Target = Target||{};//Prevent users from not transmitting Target for ( prop in Origin){ Target[prop]=Origin[prop] }
return Target; } clone(obj3,obj4)
Note that if you modify Origin's value, you will not change Target's value.
But if there are array attributes in obj3, when the calling method changes the array attributes of obj4, it will also change obj3, because it is a reference attribute: