企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持知识库和私有化部署方案 广告
## 浅拷贝 浅拷贝拷贝的是内存的地址 * Object.assign() * 结构运算符 * concat * slice ``` function shallowCopy(obj) { let target = {} for(var i in obj){ if(obj.hasOwnProperty(i)){ target[i] = obj[i] } } return target } ``` ## 深拷贝 深拷贝堆中开辟新区域,存放新对象 * JSON.parse(JSON.stringify(obj)) * 递归 * lodash 深拷贝函数 ``` function deepCopy(obj) { let target = {} for(var i in obj){ // 需要考虑是 Date 和 RegExp的情况 if(obj[i] instanceof Date) return new Date(obj) if(obj[i] instanceof RegExp) return new RegExp(obj) if( obj === null || typeof obj !== 'object') return obj if(obj.hasOwnProperty(i)){ target[i] = deepCopy(obj[i]) } } return target } ``` ### 深拷贝中 JSON.parse 存在的问题 * 会忽略 undefined * 会忽略 symbol * 不能序列化 function * 循环引用拷贝时会报错 ![](https://img.kancloud.cn/77/fa/77fa047e66b8d3c476304caf75a54b36_1192x409.png) ## 如何解决深拷贝中的循环引用 * 添加一个set集合,用于检测循环引用