Detecting and fixing circular references in JavaScript

后端 未结 15 833
庸人自扰
庸人自扰 2020-11-28 23:29

Given I have a circular reference in a large JavaScript object

And I try JSON.stringify(problematicObject)

And the browser throws

15条回答
  •  借酒劲吻你
    2020-11-29 00:20

    Pulled from http://blog.vjeux.com/2011/javascript/cyclic-object-detection.html. One line added to detect where the cycle is. Paste this into the Chrome dev tools:

    function isCyclic (obj) {
      var seenObjects = [];
    
      function detect (obj) {
        if (obj && typeof obj === 'object') {
          if (seenObjects.indexOf(obj) !== -1) {
            return true;
          }
          seenObjects.push(obj);
          for (var key in obj) {
            if (obj.hasOwnProperty(key) && detect(obj[key])) {
              console.log(obj, 'cycle at ' + key);
              return true;
            }
          }
        }
        return false;
      }
    
      return detect(obj);
    }
    

    Here's the test:

    > a = {}
    > b = {}
    > a.b = b; b.a = a;
    > isCyclic(a)
      Object {a: Object}
       "cycle at a"
      Object {b: Object}
       "cycle at b"
      true
    

提交回复
热议问题