Define “cyclic data structures”

前端 未结 9 1815
鱼传尺愫
鱼传尺愫 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 10:14
    var cyclic = {};
    cyclic.somekey = cyclic;
    cyclic.another = "Hello world!";
    

    Now you can do this, for example:

    alert(cyclic.somekey.somekey.somekey.another);
    
    0 讨论(0)
  • 2021-02-02 10:19

    A cyclic data structure is a structure that holds a reference to itself (directly or indirectly). See also http://en.wikipedia.org/wiki/Circular_reference

    Here is an example of such structure:

    var c = { value: 'abc' };
    c['c'] = c;
    c['a'] = { value: c };
    

    If you try to print its string representation recursively, you will end up with a stack overflow, because to print a value of c you must print the value of c.

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

    CYCLE: A situation in which you return to the same place where you started.

    CYCLIC DATA STRUCTURE: A data structure in which such situation might arise. For example graph,linked list (singly/doubly), dequeue, etc.

    A linked list node in JS is implemented as:

    function Node(data){
        this.data = data;
        this.next = null;
    }
    

    Now I create two such nodes as shown below:

    var node1 = new Node(10);
    var node2 = new Node(20);
    

    And link them to form a cycle.

    node1.next = node2;
    node2.next = node1;
    

    The following traversal code will enter an infinite loop which shows the existence of a cycle.

    node = node1;
    while(node!==null){
        print(node.data);
        node = node.next;
    }
    
    0 讨论(0)
提交回复
热议问题