深拷贝怎么解决循环引用?浏览器有提供解决方案吗
文章目录
要想解决循环引用,我们需要借助Set 或者Map 或者 WeekMap类型,来保存对象之间的引用关系
话不多说,直接上代码:
function isObject(obj) {
return (typeof obj === "object" || typeof obj === "function") && obj !== null;
}
function cloneDeep(source, hash = new Map()) {
if (!isObject(source)) return source;
if (hash.has(source)) return hash.get(source);
var target = Array.isArray(source) ? [] : {};
hash.set(source, target);
for (var key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
if (isObject(source[key])) {
target[key] = cloneDeep(source[key], hash);
} else {
target[key] = source[key];
}
}
}
return target;
}其实浏览器也有解决方案,只不过还未正式发布

评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论