1 function deepClone (obj) {
 2     let newObj;
 3     if (Array.isArray(obj)) { // 判断复制的目标是不是数组
 4         newObj = [];
 5     } else if (typeof obj === 'object') {
 6         newObj = {};
 7     } else {
 8         newObj = obj;
 9     };
10     if (typeof obj === 'object') {
11         for (item in obj) {
12             if(obj.hasOwnProperty(item)) {
13                 if(obj[item] && typeof obj[item] === 'object') {
14                     newObj[item] = deepClone(obj[item])
15                 } else {
16                     newObj[item] = obj[item]
17                 }
18             }
19         }
20     }
21     return newObj;
22 }
23 let obj = {name:'小明',age:20}
24 newObj = deepClone(obj)

当然,用JSON对象的parse和stringify也能完成深拷贝,但是用JSON.parse(JSON.stringify(obj))拷贝会有一个问题,就是如果数组或者对象中的属性为undefined、function和symbol时,转换过程中会被忽略

例:const obj = {name:'小明',age:20,subject:{a:100,b:null,c:undefined}}

  const newObj = JSON.parse(JSON.stringify(obj))

  console.log(newObj) // {name:'小明',age:20,subject:{a:100,b:null}}

03-14 07:38