今天在項目中遇到一個問題,需要根據數據庫中記錄的樹結構節點id獲取該記錄所在目錄節點的路徑。
大致想法,首先定義變量保存當前路徑,然后遞歸遍歷該樹節點,在遍歷的過程中將遍歷到的節點加入到當前路徑中,找到該節點后終止遞歸,最后返回路徑即可。
問題,怎樣保存當前判斷節點的路徑以及未找到節點時對路徑的處理方法。
現附上代碼:
var getPathById = function (id, catalog, callback) {
//定義變量保存當前結果路徑
var temppath = "";
try {
function getNodePath(node) {
temppath += (node.name + "\\");
//找到符合條件的節點,通過throw終止掉遞歸
if (node.id == parseInt(cataid)) {
throw ("GOT IT!");
}
if (node.children && node.children.length > 0) {
for (var i = 0; i < node.children.length; i++) {
getNodePath(node.children[i]);
}
//當前節點的子節點遍歷完依舊沒找到,則刪除路徑中的該節點
temppath = temppath.substring(0, temppath.length - 1);
temppath = temppath.substring(0, temppath.lastIndexOf("\\")) + "\\";
}
else {
//找到葉子節點時,刪除路徑當中的該葉子節點
temppath = temppath.substring(0, temppath.length - 1);
temppath = temppath.substring(0, temppath.lastIndexOf("\\")) + "\\";
}
}
getNodePath(catalog);
}
catch (e) {
callback(temppath);
}
};
改進,上面的代碼是將路徑保存在字符串中,最終直接使用即可,更好的方法是保存在數組中。
改進代碼:
var getPathById = function (id, catalog, callback) {
//定義變量保存當前結果路徑
var temppath = [];
try {
function getNodePath(node) {
temppath.push(node.name);
//找到符合條件的節點,通過throw終止掉遞歸
if (node.id == parseInt(cataid)) {
throw ("GOT IT!");
}
if (node.children && node.children.length > 0) {
for (var i = 0; i < node.children.length; i++) {
getNodePath(node.children[i]);
}
//當前節點的子節點遍歷完依舊沒找到,則刪除路徑中的該節點
temppath.pop();
}
else {
//找到葉子節點時,刪除路徑當中的該葉子節點
temppath.pop();
}
}
getNodePath(catalog);
}
catch (e) {
var result = temppath.join("\\");
callback(result);
}
};
最后,只是給大家提供思路,過濾條件可以自己去定義
