1 <script type="text/html"> 2 var obj1 = { 3 'name': '撩课', 4 'age': 2 5 }; 6 var obj2 = {}; 7 8 for(var key in obj1){ 9 obj2[key] = obj1[key]; 10 } 11 obj1.age = 30; 12 console.log(obj1); 13 console.log(obj2); 14 15 </script>
<script type="text/html"> var obj1 = { 'name': '撩课', 'age': 2 }; var obj2 = {}; Object.assign(obj2, obj1);//合并 obj2.age = 100; console.log(obj1); console.log(obj2); </script>
The above two kinds is shallow copy
. 1 <Script> 2 var P = { . 3 'name': 'John Doe' , . 4 'Qucik Facts Pets': [ 'ha', 'Cai', 'Want small' ] . 5 }; . 6 . 7 var copyP = {}; . 8 Object.assign (copyP, P); . 9 10 p.pets.push ( 'I I nice and large river' ); . 11 the console.log (copyP); 12 is the console.log (P); 13 is </ Script> 14 15 will increase, affecting the original data
Deep copy
. 1 <Script> 2 var obj = { . 3 name: 'stitch courses' , . 4 Age: 18 is , . 5 Friends: [ 'flower', 'black' ], . 6 goodF: { . 7 name: 'Small stitch' , . 8 Age :. 19 , . 9 address: 'Shanghai' , 10 Qucik Facts Pets: [{name: 'potatoes'}, {name: 'potato' }]}, . 11 BIR: new new a Date () 12 is }; 13 is 14 var newobj =The JSON.parse (the JSON.stringify (obj)); 15 by such a deep copy is, will not affect each 16 obj.goodF.pets [0] .name = 'ha ha ha ha' ; . 17 the console.log (newobj); 18 is the console.log (obj); . 19 20 is // regardless of change new, old and defects do not affect each other (do recursive) 21 is </ Script>