手写深拷贝代码
const obj1 = { age: 18, name: '齐晶', address: { city: 'beijing' }, arr = [1, 2, 3] } const obj2 = deepClone(obj1) obj2.address.city = 'chengdu' console.log(obj1.address.city) // 深拷贝 function deepClone(obj = {}) { if(typeof obj != 'object' || typeof obj ==null) { // 如果obj不是数组或对象 ,或者obj是null,直接返回 return obj } // 初始化返回结果 let result if(obj instanceof Array) { result = [] } else { result = {} } for (let key in obj) { // 保证key不是原型的属性 if(obj.hasOwnProperty(key)){ // 递归 result[key] = deepClone([obj[key]]) } } // 返回结果 return result }