Skip to content
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

Open
Sunny-117 opened this issue Nov 3, 2022 · 5 comments
Open

判断对象是否存在循环引用 #80

Sunny-117 opened this issue Nov 3, 2022 · 5 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@jiamianmao
Copy link

JSON.stringify 就可以

@lxq-mdc
Copy link

lxq-mdc commented Jul 25, 2023

`

 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.       

`

@kangkang123269
Copy link

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

@Liu6625
Copy link

Liu6625 commented Oct 17, 2023

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)
}

@gswysy
Copy link

gswysy commented Mar 5, 2024

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)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

6 participants