跳到主要内容

循环引用

2024年04月09日
柏拉文
越努力,越幸运

一、认识


二、实现


2.1 WeakSet

function isCycle(obj) {
const weakSet = new WeakSet();
let detected = false;
const detect = (obj) => {
if (obj && typeof obj !== "object") {
return;
}
if (weakSet.has(obj)) {
detected = true;
return detected;
}
weakSet.add(obj);
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
detect(obj[key]);
}
}
};
detect(obj);
return detected;
}

const obj = {
name: "哈哈",
age: 23,
};
obj.objs = obj;
console.log(isCycle(obj));