【JS】(数组、对象)深拷贝函数的封装

时间:2023-01-22 19:56:33
 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))拷贝会有一个问题,就是如果数组或者对象中的值为null时,拷贝后值变为undefined