手写js深拷贝 (面试手写重中之重)
1 function deepClone(obj) { 2 let newObj; 3 // 判断数据类型 4 if (Array.isArray(obj)) { 5 newObj = []; 6 for (let i = 0; i < obj.length; i++) { 7 // 判断数组中的元素数据类型 8 if (Array.isArray(obj[i])) { 9 // 递归 10 newObj[i] = deepClone(obj[i]) 11 } else { 12 newObj[i] = obj[i] 13 } 14 } 15 } else { 16 newObj = {}; 17 for (let key in obj) { 18 // 判断对象中的属性值的数据类型 19 if (typeof obj[key] === 'object' && obj[key] !== null) { 20 newObj[key] = deepClone(obj[key]) 21 } else { 22 newObj[key] = obj[key] 23 } 24 } 25 } 26 27 return newObj; 28 } 29 let obj = { 30 name: '万仙山', 31 age: 19, 32 hobby: { title: "电影爱好者" }, 33 say: function () { console.log('hello'); } 34 } 35 // let obj = {name:'万仙山', age:19, sex:null, say:function(){console.log('hello');}} 36 let res = deepClone(obj) 37 console.log(res); 38 // res.say() 39 res.hobby.title = '游戏终结者'; 40 console.log(obj);