JavaScript中深拷贝的实现方法

js实现递归深拷贝的demo

1.Object.assin()此方法不适合业务复杂场景拷贝

2.lodash中的deepClone方法

3.JSON.parse(JSON.Stringfy(obj))注意此方法的特殊应用场景

4.jQuery 中的extentd方法

5.递归(见下列):

 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         // const Obj = {
11 //   name: 'tom',
12 //   age: 18,
13 //   phone: '183213211'
14 // }
15 // let test = ''
16 // Object.keys(Obj).forEach((item,index)=>{
17 //   console.log(item);
18 //   if(Object.keys(Obj).length !== index+1){
19 //     test += item+'='+ Obj[item]+','
20 //   }else{
21 //     test += item+'='+ Obj[item]
22 //   }
23 // })
24 // console.log(test);
25 
26 // 递归深拷贝
27 
28 var obj = {
29   arr1 : [1,2,3],
30   fn: function(){
31       console.log('我是一个方法')
32   },
33   j: {
34       bc: 'asdfa',
35       ba: [
36           {df: 88,
37             da: {
38                 dj: 00
39             }
40         },
41           [23,77]
42       ],
43       fn: function (){
44           return 232
45       }
46   },
47   a : '我是普通属性'
48 }
49 
50 // 现在我要把obj字面量创建里的属性深拷贝( 属性值是引用类型也要深拷贝 )
51 function deepClone(obj){
52   // 根据类型制造一个新的数组或对象 => 指向一个新的空间
53       // 由于数组的typeof也是'object',所以用Array.isArray(obj)
54   var new_obj = Array.isArray(obj) ? [] : {};
55   // 首先判断obj的类型
56       // 普通类型
57   if( typeof obj != 'object' ){
58       // 这里不能直接返回obj,不然就是浅拷贝的性质
59       return  new_obj = obj
60   }
61     //引用类型
62           //数组
63   if(obj instanceof Array ){
64       for(i = 0; i < obj.length; i++ ){
65           new_obj[i] = obj[i];
66           if(typeof new_obj[i] == 'object'){
67               deepClone(new_obj[i])
68           }
69       }
70   }else{ //对象
71       for (let key in obj) {
72           if (obj.hasOwnProperty(key)) {
73               // 对象中的数组和对象
74               if (typeof obj[key] == 'object') {
75                   new_obj[key] = deepClone(obj[key]); 
76               }else{//对象中没有引用类型
77                   new_obj[key] = obj[key]
78               }  
79           }
80       }
81   }
82   return new_obj;
83 }
84 var deepClone = deepClone(obj);
85 console.log(deepClone);
86 // 测试是不是深拷贝
87 // obj.fn = '我改变了方法属性';
88 // console.log(obj); //{arr1: Array(3), fn: ƒ, a: "我是普通属性", c: "我新增了一个属性"}
89 // console.log(deepClone); // 还是 {arr1: Array(3), fn: ƒ, a: "我是普通属性"}
90     </script>
91 </body>
92 </html>
时间如白驹过隙,忽然而已,且行且珍惜......
原文地址:https://www.cnblogs.com/UnfetteredMan/p/14534376.html