萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 閉包遞歸遍歷樹狀數組查找節點

場景

菜單數據為樹狀 JSON 結構,需根據 id 查找對應節點並返回 text(名稱)。

數據結構示例

var menus = [{
    "id": 28, "text": "公司信息", "children": [
        {"id": 1, "text": "公司文化"},
        {"id": 2, "text": "招聘計劃"},
        {"id": 6, "text": "公司新聞", "children": [
            {"id": 47, "text": "行業新聞"}
        ]},
        {"id": 11, "text": "內部新聞", "children": [
            {"id": 24, "text": "行政信息"},
            {"id": 27, "text": "高層指示"}
        ]},
        {"id": 22, "text": "聯系我們"},
        {"id": 26, "text": "產品展示", "children": [
            {"id": 32, "text": "電力產品"},
            {"id": 33, "text": "配件介紹"}
        ]}
    ]
}];

閉包遞歸實現

/**
 * 在樹狀菜單中查找指定 id 的節點文本
 * @param {Array} menus - 菜單節點數組
 * @param {number|string} targetId - 目標 id
 * @returns {string} 找到返回 text,否則空串
 */
function getMenuName(menus, targetId) {
    var result = ''; // 閉包變量,保存查找結果

    // 內部遞歸函數(利用閉包訪問 result、targetId)
    function traverse(nodes) {
        for (var i = 0, len = nodes.length; i < len; i++) {
            var node = nodes[i];
            if (node.id == targetId) { // == 允許數字/字串比較
                result = node.text;
                return true; // 找到,冒泡終止遞歸
            }
            if (node.children && node.children.length > 0) {
                if (traverse(node.children)) return true; // 子樹找到,向上傳遞終止信號
            }
        }
        return false; // 當前樹未找到
    }

    traverse(menus);
    return result;
}

// 測試
console.log(getMenuName(menus, 32)); // "電力產品"
console.log(getMenuName(menus, 99)); // ""

關鍵點解析

  • 閉包捕獲 result:內部函數 traverse 共享外層 result 變量,找到時賦值,外層函數最終返回。
  • 返回布爾值終止遞歸:一旦找到,逐層 return true 立即結束所有遞歸調用,避免無謂遍歷。
  • 參數命名:避免 id 等保留字,用 targetId。
  • 容錯:node.children && node.children.length 防御空數組/未定義。

現代寫法:生成器 + 扁平化(更簡潔)

function* flattenTree(nodes) {
    for (const node of nodes) {
        yield node;
        if (node.children?.length) yield* flattenTree(node.children);
    }
}

function getMenuNameModern(menus, targetId) {
    for (const node of flattenTree(menus)) {
        if (node.id == targetId) return node.text;
    }
    return '';
}
  • ES6 Generator 將樹展平為序列,邏輯線性化,無需閉包手動控制流。
  • 支援 for...of 直接消費,可配合 .find()(需轉陣列)或手寫循環。

性能優化:建立 ID 映射表(適用於頻繁查詢)

function buildIdMap(nodes, map = {}) {
    for (const node of nodes) {
        map[node.id] = node.text;
        if (node.children?.length) buildIdMap(node.children, map);
    }
    return map;
}

const menuMap = buildIdMap(menus); // 一次性構建
function getMenuNameFast(id) { return menuMap[id] || ''; } // O(1) 查詢

若查詢頻繁、樹不常變,預構建 Map 最優;單次查詢遞歸遍歷即可。

copyright © 萬盛學電腦網 all rights reserved