gpt4 book ai didi

javascript - 树结构 - Javascript - parent ?

转载 作者:行者123 更新时间:2023-11-28 13:42:21 25 4
gpt4 key购买 nike

简单来说

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

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

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

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com