菜單數據為樹狀 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 '';
}
for...of 直接消費,可配合 .find()(需轉陣列)或手寫循環。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 最優;單次查詢遞歸遍歷即可。