[英]Generic tree implementation in Javascript
是否有人知道JavaScript的通用樹(節點可能有多個子節點)實現?
應該能夠做到至少這些東西,
一些類似於鄰接列表模型的實現。
背景:我需要基於JavaScript的分層數據存儲我的網頁我找不到一個很好的通用樹的JavaScript實現,所以我做的是我使用ajax使用Adjacency List Model和php將分層數據存儲到數據庫中。 當用戶在同一個瀏覽器的兩個選項卡中打開同一頁面或在兩個不同的瀏覽器中打開頁面時,問題就出現了,因為兩個實例都在寫同一個表從同一個表讀取,這導致我出現問題。回答我的問題。
編輯:在任何時候, 性能都不是我的約束,我不會有超過50個條目。
你可以嘗試這個: https : //github.com/afiore/arboreal
或者這個: https : //github.com/mauriciosantos/buckets/ (只有二進制搜索樹,但其他數據結構)
如果你需要更復雜的東西,你需要編寫自己的庫(或至少一個對象與你所描述的所有方法)。
編輯:
這是我實現樹功能的簡單代碼。 刪除所有后代並刪除所有子項實際上是相同的......所以:
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(或其他支持控制台的瀏覽器)中運行它。
雖然您確實說過“通用樹”,但對於已經內置的DOMParser
,您的具體要求聽起來很簡單。
我尊重其他程序員的意見,但我認為你可以試試DOM
,看看它是否適合你。
以下是有關其工作原理的簡單說明:
var tXML="<root><fruit><name>apple</name><color>red</color></fruit><fruit><name>pear</name><color>yellow</color></fruit></root>";
var tree=(new DOMParser).parseFromString(tXML,"text/xml");
//get descendants
var childs=tree.documentElement.childNodes;
for(var i=0;i<childs.length;i++)
{
if(childs[i].nodeName=="fruit")
{
document.write(childs[i].getElementsByTagName("name")[0].textContent);
document.write(": ");
document.write(childs[i].getElementsByTagName("color")[0].textContent);
document.write("<br />");
}
}
//get child node
var appl=tree.documentElement.getElementsByTagName("fruit")[0];
document.write(appl.getElementsByTagName("name")[0].textContent+"<br />");
//get parent node
document.write(appl.parentNode.nodeName);
document.write("<br />");
//remove child node
if(tree.documentElement.getElementsByTagName("color").length>1)
{
var clr=tree.documentElement.getElementsByTagName("color")[1];
clr.parentNode.removeChild(clr);
}
document.write("<textarea>"+(new XMLSerializer).serializeToString(tree)+"</textarea><br />");
//remove descendants
while(tree.documentElement.childNodes.length>0)
{
tree.documentElement.removeChild(tree.documentElement.childNodes[0]);
}
document.write("<textarea>"+(new XMLSerializer).serializeToString(tree)+"</textarea>");
我沒有“簡化”那些長函數名稱,所以你可能會有更好的想法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.