-
-
Notifications
You must be signed in to change notification settings - Fork 229
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
判断对象是否存在循环引用 #80
Comments
JSON.stringify 就可以 |
`
` |
function isCyclic(obj) {
let seenObjects = new WeakSet();
function detect (obj) {
if (typeof obj === 'object') {
if(seenObjects.has(obj)) {
return true;
}
seenObjects.add(obj);
for(let key in obj) {
if (detect(obj[key])) return true;
}
}
return false;
}
return detect(obj);
}
let cyclicObj1 = {};
cyclicObj1.selfRef = cyclicObj1;
let cyclicObj2 = { a: { b: null } };
cyclicObj2.a.b = cyclicObj2.a;
console.log(isCyclic(cyclicObj1)); // 输出:true
console.log(isCyclic(cyclicObj2)); // 输出:true
console.log(isCyclic({})); // 输出:false |
function isCyclic(obj) {
let map = new WeakSet();
const detect = (obj) => {
if(typeof obj === 'object' && obj !== null){
if(map.has(obj)){
return true;
}
map.add(obj);
for(let key in obj){
if(detect(obj[key])){
return true;
}
}
}
return false;
}
return detect(obj)
} |
|
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
No description provided.
The text was updated successfully, but these errors were encountered: