Home > Article > Web Front-end > Understanding of js cloning: deep cloning and shallow cloning (code example)
The content of this article is to introduce the understanding of js cloning: deep cloning and shallow cloning (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
<script> //判断是不是原始值//判断是数组还是对象//建立相应的数组或对象 var obj = { name: '辣鸡', sex: 'male', card: ['laobi', 'feiwu'], wife: { name: '智障', son: { name: '彩笔' } } } var obj1 = {} function deepClone(Origin, Target) { var Target = Target || {}, toStr = Object.prototype.toString, arrStr = '[object Array]'; for(var prop in Origin) { //第一步,判断对象是不是原始值 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>
Note:Method to determine whether it is a prototype , first think of the for in and hasProperty methods, and then use typeof(Origin[prop]) =='object',
Methods to judge arrays and objects, then There are three types, constructor , toString call , instanceof
What is used here is toString.call(Origin[prop]=='arrStr'), which is actually to determine whether it is [object Array]
Finally, the recursion uses the callback deepClone() method, Creates the corresponding array and object
function deepClone(Origin, Target) { var Target = Target || {}, toStr = Object.prototype.toString, arrStr = '[object Array]'; for(var prop in Origin) { //第一步,判断对象是不是原始值 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; }
var obj3={ name:'abc', sex:'boy', height:178} var obj4={} function clone(Origin,Target){ var Target = Target||{};//防止用户不传Target for ( prop in Origin){ Target[prop]=Origin[prop] } return Target; } clone(obj3,obj4)
It should be noted that if you modify the Origin value, the value of Target will not be changed
But if there is an array attribute in obj3, when calling the method to change the array attribute of obj4, obj3 will also be changed, because it is a reference attribute :
##
The above is the detailed content of Understanding of js cloning: deep cloning and shallow cloning (code example). For more information, please follow other related articles on the PHP Chinese website!