我將以我想要做的事開始我的問題。我有一個數組(名稱列表),在我的數組中我持有對象。這些對象由人的姓名(傑克,簡,詹姆斯,丹尼爾等)以及這些人相關的數組組成(傑克與丹尼爾等有關)。當然,一個人可以與多於一個人有關,但兩個孩子不能關聯。我想把它們留在一棵樹中,我希望這棵樹能夠根據關係。我想從與關係最密切的人開始(例如:丹尼爾與7人有關)。我知道可能有超過1人的關係最密切。但爲了簡單的問題,我問,讓我們只是說我知道它是誰,我會通過它作爲mostRelated。使用數組創建樹
This is just an example of what I want to do
這是我有這麼far.But我不知道如何進一步它。
//my array of names is nameList
//to check who they are related to nameList.relatedTo
function Node(names) {
this.data = names;
this.parent = null;
this.children = [];
}
function CreateTree(nameList, mostRelated)
{
this._root=mostLinked;
for(var i=0; i < nameList[i].length;i++)
{
node= new Node(nameList[i]);
if(nameList[i].isChecked!)//if already add to the tree
{
if(nameList[i].isRelated)//to check if they have any relation
{
for(var j=0; i < nameList[i].relatedTo[j].length;j++)
{
if(nameList[i].relatedTo.isChecked!)
{
nameList[i]=Node.parent;
Node.children.push(nameList[i].relatedTo[j]);
nameList[i].isChecked=true;
}
}
}
}
}
}
名稱列表看起來像這樣
nameList
this.name;
this.relatedTo=[];
this.related=false;
this.checked=false;
爲此使用樹不是正確的數據結構 - 如果兩個孩子也有關係?您需要使用圖表/地圖 – ControlAltDel
您的設置已遍佈全球。你不是已經確定誰是誰的父母/孩子嗎?爲了在已經提供信息的地方繪製數據圖,您已經制作了一張圖。舉一個'nameList'的一個元素的例子。我可能會誤解你的目標。 – Andrew
@ControlAltDel,感謝您的建議。但我可以讓2個孩子不相關。我改變了這個問題。 – JJD