9.深克隆2.html 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>Document</title>
  7. </head>
  8. <body>
  9. <script>
  10. var news = {
  11. name: '赵家锐',
  12. age: 29,
  13. msg: {
  14. address: '哈尔滨',
  15. sex: '男'
  16. }
  17. }
  18. function deepClone(obj) {
  19. // 定义一个空对象 用于接收深拷贝后的结果
  20. var obj1 = {};
  21. for(var key in obj) {
  22. // 判断对象中的每一项是不是引用数据类型
  23. if(typeof(obj[key]) == 'object'){
  24. // 是引用类型
  25. obj1[key] = deepClone(obj[key]);
  26. } else {
  27. // 不是引用类型
  28. obj1[key] = obj[key];
  29. }
  30. }
  31. return obj1;
  32. }
  33. var new1 = deepClone(news);
  34. new1.msg.address = '北京';
  35. console.log(new1,'new1')
  36. console.log(news,'news')
  37. // console.log(deepClone(news))
  38. </script>
  39. </body>
  40. </html>