javascript - 树结构 - Javascript - parent ?

标签 javascript

简单来说

我有一个由对象组成的树结构。

是否可以构建该树并向每个对象添加对其父对象的引用?

我知道引用适用于对象,但我不确定在这种情况下是否有效?

我希望能够写出这样的东西

currentLevel = this.getParent();

另一个例子是

this.getChildList().addChild({name: test,parent: this}) 

无需复制并从第一个树创建多个树。

第二个问题

引用如何与数组一起工作?它们被视为对象还是取决于它们的内容?

第三个问题

通过字符串 JSON 序列化将树保存在浏览器的缓存中是否会破坏引用?

最佳答案

可以通过创建“TreeNode”类来做到这一点:

var TreeNode = (function(){

    //keep track of parent node
    TreeNode.prototype.parent = null;
    //keep track of children
    TreeNode.prototype.children = [];

    function TreeNode(parent) {
        if(parent !== undefined) {
            if(this.setParent(parent)) {
                this.parent.addChild(this);
            }
        }
        //...
    }

    TreeNode.prototype.setParent = function(parent) {
        //add some sort of check to make sure it is a `TreeNode`
        if(parent instanceof TreeNode) {
            this.parent = parent;
            return true;
        }
        return false;
    }

    TreeNode.prototype.addChild = function(child) {
        //add some sort of check to make sure it is a `TreeNode`
        if(child instanceof TreeNode) {
            this.children.push(child);
            child.setParent(this);
        }
    }

    TreeNode.prototype.getParent = function(){
        return this.parent;
    }

    TreeNode.prototype.getChildren = function(){
        return this.children;
    }

    return TreeNode;

})();

然后您可以以此为基础进行扩展。

示例代码:

var node_a = new TreeNode();
var node_b = new TreeNode(node_a);
var node_c = new TreeNode(node_a);

console.log(node_a.getParent(), node_c.get_parent()); //null , node_a        
console.log(node_a.getChildren()); //[node_b, node_c]
<小时/>

这只是一个开始,它需要更多扩展:-)

关于javascript - 树结构 - Javascript - parent ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17111520/

相关文章:

javascript - React Native - 获取当前时间并创建动态 x(时间)轴?

javascript - AngularJS 中未定义 memberID

javascript - 切换 lang 属性

javascript - 没有击中 javascript 断点

javascript - webpack 通过插件在编译前添加文件

javascript - 如何从跨度传递/提取文本?

javascript - $scope 不调用内部函数

javascript - 每 3-4 个字符插入一个空格

javascript - 在 typescript+Angular 项目中使用 requirejs (-m amd) 的优点和缺点

javascript - Javascript 中的正则表达式对类别中的项目进行分组