js-challenges icon indicating copy to clipboard operation
js-challenges copied to clipboard

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

Open Sunny-117 opened this issue 2 years ago • 5 comments

Sunny-117 avatar Nov 03 '22 08:11 Sunny-117

JSON.stringify 就可以

jiamianmao avatar May 22 '23 07:05 jiamianmao

`

 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.       

 

`

lxq-mdc avatar Jul 25 '23 03:07 lxq-mdc

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

kangkang123269 avatar Sep 01 '23 03:09 kangkang123269

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

Liu6625 avatar Oct 17 '23 07:10 Liu6625

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

Aurora-GSW avatar Mar 05 '24 01:03 Aurora-GSW