Define “cyclic data structures”

前端 未结 9 1814
鱼传尺愫
鱼传尺愫 2021-02-02 09:33

At the JSON site it says

JSON does not support cyclic data structures, so be careful to not give cyclical structures to the JSON stringifier.

<
相关标签:
9条回答
  • 2021-02-02 09:58
    js> var a = {label:"a", next:null};
    js> var b = {label:"b", next:a};
    js> a.next = b; // cycle is created here
    [object Object]
    js> print(a.next.label);
    b
    js> print(a.next.next.label);
    a
    js> print(a.next.next.next.label);
    b
    js> print(a.next.next.next.next.label);
    a
    
    0 讨论(0)
  • 2021-02-02 10:05

    If you imagine the members of the data structure laid out as a graph, a cyclic data structure is where a member refers back to another one or the structure itself.

    For example:

    var obj = new Object();
    
    obj.left = new Object();
    
    obj.left.left = obj;
    

    This is impossible to represent in JSON, you would need to refer to the outer {} part somehow:

    { "left": { "left": ??? } }
    
    0 讨论(0)
  • 2021-02-02 10:05

    if you have:

    var a = {value: 'a'};
    var b = {value: a};
    var c = {value: a};
    

    In JSON for b it would look like:

    "{value: {value: 'a'}}"
    

    In JSON for c it would look like:

    "{value: {value: 'a'}}"
    

    No pointers.

    0 讨论(0)
  • 2021-02-02 10:10

    I guess the textbook example of a cyclic structure is the doubly-linked list. Each element points to the previous and next elements in the list. This means each element forms a cycle with the previous and next element.

    A --> B  --> C
    A <-- B  <-- C
    

    (Here each A, B, C although written twice is one object.)

    A points to B, as next in the list. B points to A as previous in the list. So there is a cycle from A to B and back to A. The same is true for every element in the list, with elements not at the head or tail beloning to two cycles.

    One solution to serializing lists like this is to use IDs to represent each object. This removes the cycles in the structure. We could then write out

      list: {
         items:
          { id:"a", value1: ... etc },
          { id:"b", values .... },
          { id:"c", values .... }
         links:
           { elem:"a", next:"b" },
           { elem:"b", next:"c", prev: "a"},
           { elem:"c", prev:"b" }
      }
    
    0 讨论(0)
  • 2021-02-02 10:10

    A data structure with a cyclic graph: http://en.wikipedia.org/wiki/Cycle_graph

    0 讨论(0)
  • 2021-02-02 10:12

    The object contains a cycle, i.e., it refers to itself or, more generally, some object to which it refers either directly or through some property is the original object.

     var $this =  { };
     $this["self"] = $this;
    

    or more likely

     var child = { parent: null };
     var parent = { child: child };
     child.parent = parent;
    
    0 讨论(0)
提交回复
热议问题