js-challenges
js-challenges copied to clipboard
判断对象是否存在循环引用
JSON.stringify 就可以
`
function hasCycle(obj) {
let seenObjects = [];
function detect(obj) {
if (obj && typeof obj === 'object') {
if (seenObjects.indexOf(obj) !== -1) {
return true;
}
seenObjects.push(obj);
for (let key in obj) {
if (obj.hasOwnProperty(key) && detect(obj[key])) {
return true;
}
}
}
return false;
}
return detect(obj);
}
const obj1 = {};
obj1.self = obj1;
console.log(hasCycle(obj1)); // true
const obj2 = {
a: 1,
b: {
c: 2
}
};
console.log(hasCycle(obj2)); // false.
`
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)
}
function isCyclic(obj) {
let set = new Set()
function step(o) {
if (set.has(o)) {
return true
}
set.add(o)
for (const key in o) {
if (typeof o[key] === 'object') {
if (step(o[key])) return true
}
}
return false
}
return step(obj)
}