/** * 深拷贝 */ const obj1 = { age: 20, name: ‘xxx‘, address: { city: ‘beijing‘ }, arr: [‘a‘, ‘b‘, ‘c‘] } const obj2 = deepClone(obj1) obj2.address.city = ‘shanghai‘ obj2.arr[0] = ‘a1‘ console.log(obj1.address.city) // beijing console.log(obj1.arr[0]) //a /** * 深拷贝的实现 */ function deepClone(item) { // 判断是否为需要遍历的对象 if (typeof item !== ‘object‘ || item == null) { // 直接返回 return item } // 初始化一个返回结果 let result; // 判断是数组还是对象 初始化result if (item instanceof Array) { result = [] } else { result = {} } // 递归 注意是要循环对象的所有可枚举属性 // 然后再使用hasOwnProperty来忽略掉不是自身的继承的属性 for (let key in item) { if (item.hasOwnProperty(key)) { // 递归调用! result[key] = deepClone(item[key]); } } return result }
要点:
原文:https://www.cnblogs.com/yangyu-1997/p/15165004.html