递归实现深拷贝
hashMap部分解决对象循环引用问题var obj { name: Jack, test: function () { console.log(obj); }, zero: 0, hobby: [null, undefined, 0, haha] } function copy (source, hashMap new WeakMap()) { //判断是否已经拷贝过 if (hashMap.get(source)) return hashMap.get(source) /* 实现方式一 // 获取source数据类型 const type1 ((Object.prototype.toString.call(source)).split( )[1]).slice(0,-1) let target; switch (type1) { case Object: target {} break; case Array: target [] break; } */ //实现方式二 let target new source.constructor() hashMap.set(source, target) for (const key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { const element source[key]; const type ((Object.prototype.toString.call(element)).split( )[1]).slice(0,-1) if (type Object) { target[key] copy(element,hashMap) } else if (type Array) { target[key] copy(element,hashMap) } else target[key] element } } return target } let o copy(obj) //循环引用 let test1 {},test2 {}; test1.test2 test2 test2.test1 test1 console.log(copy(test2));
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2410385.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!