Home > Article > Web Front-end > What is the difference between shallow cloning and deep cloning in JS
This article shares an important knowledge point about cloning in JavaScript, which has certain reference value. I hope it will be helpful to everyone’s learning
Clone points in JavaScript There are two types: shallow cloning and deep cloning. They both traverse the value first to determine whether it is an original value or a reference value. The original value is copied directly. The reference value is first determined whether it is an object or an array and then cloned.
Original value : Values like Undefined, Null, Boolean, Number and String are called original values
Reference values: Values like object array functions are called reference values
Shallow clone
Mainly assigns the address of the data to the corresponding variable but does not assign the specific value to the corresponding variable. The variable will change as the data changes
<script> var obj={ name:"张三", age:18, sex:"male", grade:[' Math:90','English:88','Chinese:80'] } var obj1={} function clone(origin,target){ var target=target||{}; for(var prop in origin){ target[prop]=origin[prop]; }//防止用户不传target对象,给了参数就直接用,不给就当空对象, return target; } clone(obj,obj1); </script>
Result
obj1 cloned the value of obj. When adding a value to obj's grade, the value of obj1's grade also changed
Deep cloning
assigns data to corresponding variables, so a new data is generated and has a new address. Changes to the original data will not affect the new Data
<script type="text/javascript"> var obj={ name:"张三", age:18, sex:"male", grade:[' Math:90','English:88','Chinese:80'] } var obj1={} function deepClone(origin,target){ var target=target||{}, toStr=Object.prototype.toString,//简化代码 arrStr="[Object Array]"; for(var prop in origin){//从原始 origin 拷贝到 target if(origin.hasOwnProperty(prop)){///先判断是不是原型上的属性,如果是false 就是原型上的 { if(typeof(origin[prop])!== "null" && 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]; } } } return target; } </script>
Result
obj1 cloned the value of obj. When adding a value to obj’s grade, obj1’s The value of grade will not change
Summary: The above is the content of this article, I hope it will be helpful to everyone's learning.
The above is the detailed content of What is the difference between shallow cloning and deep cloning in JS. For more information, please follow other related articles on the PHP Chinese website!