I need to create a custom tree data-structure using JavaScript

前端 未结 4 1862
悲&欢浪女
悲&欢浪女 2021-02-10 18:14

I looked up this basic format for a tree structure in javascript:

function Tree(parent, child, data) {
    this.parent = parent;
    this.children = child || [];         


        
4条回答
  •  耶瑟儿~
    2021-02-10 18:44

    The most managable approach for this structure is IMHO to use linked lists.

    function Node(parentNode)
    {
        this.Parent=parentNode;
        this.FirstChild=null;
        this.LastChild=null;
        this.PreviousSibling=null;
        this.NextSibling=null;
    }
    Node.prototype.AddChild=function(child)
    {
        child.Parent = this;
        child.PreviousSibling = this.LastChild;
        if (this.LastChild != null)
            this.LastChild.NextSibling = child;
        this.LastChild = child;
        if (this.FirstChild == null)
            this.FirstChild = child;
    }
    

    To loop through children, do something like this:

    function GetChildren(node)
    {
        var result=new Array();
        var child=node.FirstChild;
        while(child)
        {
            result.push(child);
            child=child.NextSibling;
        }
        return result;
    }
    

    (edit) The "Node"-object is just an example and it should have meaningful properties added to it. Using this as a base for all objects in your tree, it may have any depth without making it more complex. You can add more functions, like GetChildByName, RemoveChild, and so on.

提交回复
热议问题