js中樹結構根據條件尋找節點返回節點路徑的一些思路

來源:互聯網
上載者:User

標籤:遞迴   字元   call   ppa   條件   []   highlight   通過   目錄   

  今天在項目中遇到一個問題,需要根據資料庫中記錄的樹結構節點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);    }};

  最後,只是給大家提供思路,過濾條件可以自己去定義

js中樹結構根據條件尋找節點返回節點路徑的一些思路

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.