我正在尝试在代码中调用递归函数。循环第一次执行,但是在函数内部调用的递归函数不起作用。 这是我的代码:
function buildDynamicMenu(elements,parentId)
{
branch =new Array();
elements.forEach(function(element){
if (element['parent_id'] == parentId) {
children = buildDynamicMenu(elements, element['menu_id']); //Recursive function not working
if (children) {
element['children'] =children;
}
branch = element;
}
});
return branch;
}
var parentId=0;
buildDynamicMenu(data); // Array data
我添加了用于此逻辑的示例数组,该数组具有菜单和子菜单ID,我们必须调用递归函数来遍历所有子数组
Array
(
[0] => Array
(
[menu_id] => 1
[menu_name] => Home
[parent_id] => 0
[link] => #home
)
[1] => Array
(
[menu_id] => 2
[menu_name] => Web development
[parent_id] => 0
[link] => #web-dev
)
[2] => Array
(
[menu_id] => 3
[menu_name] => WordPress Development
[parent_id] => 2
[link] => #wp-dev
)
[3] => Array
(
[menu_id] => 4
[menu_name] => About w3school.info
[parent_id] => 2
[link] => #w3school-info
)
[4] => Array
(
[menu_id] => 7
[menu_name] => Javascript
[parent_id] => 2
[link] => #
)
[5] => Array
(
[menu_id] => 8
[menu_name] => Plugins
[parent_id] => 7
[link] => #plugin-dev
)
)
答案 0 :(得分:0)
似乎没有指向buildDynamicMenu的导出。检查“ this”中是否有一个。尝试将buildDynamicMenu函数分配给某些const并执行对其的调用。
好吧,这是我的演示功能在nodejs打字稿中运行得很好:
function recursieve (p) {
console.log('in recursieve ', p);
if (p > 0) {
recursieve (--p);
} } recursieve (10);// rec call
因此,我认为您的代码中存在两个问题: 1.“ this”未指向该功能。 2.递归条件,例如元素为空,或者id不匹配。