有人知道 JavaScript 的通用树(节点可能有多个子节点)实现吗?
它至少应该能够做这些事情,
- 获取父节点。
- 获取子节点。
- 获取所有后代。
- 删除所有后代。
- 删除子节点。
类似于邻接表模型的一些实现。
背景: 我的网页需要基于 JavaScript 的分层数据存储,我找不到通用树的良好 JavaScript 实现,所以我所做的是使用 ajax 使用邻接列表将分层数据存储到数据库中模型和 php。当用户在同一个浏览器的两个选项卡中打开同一个页面或在两个不同的浏览器中打开该页面时,问题就出现了,因为这两个实例都写入同一个表,从同一个表读取,这导致我出现问题任何可能的解决方法也回答我的问题。
编辑: 性能 在任何时候我都不会有超过 50 个条目。
最佳答案
你可以试试这个:https://github.com/afiore/arboreal
或者这个:https://github.com/mauriciosantos/buckets/ (只有二叉搜索树,还有其他数据结构)
如果您需要更复杂的东西,您将需要编写自己的库(或至少一个包含您描述的所有方法的对象)。
编辑:
这是我实现树功能的简单代码。 Remove all descendants 和 remove all children 其实是一样的……所以:
function Node(value) {
this.value = value;
this.children = [];
this.parent = null;
this.setParentNode = function(node) {
this.parent = node;
}
this.getParentNode = function() {
return this.parent;
}
this.addChild = function(node) {
node.setParentNode(this);
this.children[this.children.length] = node;
}
this.getChildren = function() {
return this.children;
}
this.removeChildren = function() {
this.children = [];
}
}
var root = new Node('root');
root.addChild(new Node('child 0'));
root.addChild(new Node('child 1'));
var children = root.getChildren();
for(var i = 0; i < children.length; i++) {
for(var j = 0; j < 5; j++) {
children[i].addChild(new Node('second level child ' + j));
}
}
console.log(root);
children[0].removeChildren();
console.log(root);
console.log(root.getParentNode());
console.log(children[1].getParentNode());
在 Chrome(或其他支持控制台的浏览器)中运行它。
关于javascript - Javascript 中的通用树实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12036966/