我想了解以下示例,因此对我来说非常清楚。不幸的是,我的头卡在了线上:.forEach (c => (node [c.id] = makeTree (categories, c.id)))。有人可以给我一个提示吗?
let categories = [
{ id: 'animals', parent: null },
{ id: 'mammals', parent: 'animals' },
{ id: 'cats', parent: 'mammals' },
{ id: 'dogs', parent: 'mammals' },
{ id: 'chihuahua', parent: 'dogs' },
{ id: 'labrador', parent: 'dogs' },
{ id: 'persian', parent: 'cats' },
{ id: 'siamese', parent: 'cats' }
];
let makeTree = (categories, parent) => {
let node = {};
categories
.filter(c => c.parent == parent)
.forEach(c => (node[c.id] = makeTree(categories, c.id)));
return node;
};
console.log(makeTree(categories, null));
expected:
{
animals: {
mammals: {
dogs: {
chihuahua: null
labrador: null
},
cats: {
persian: null
siamese: null
}
}
}
}
最佳答案
代码可以等效地(并且,恕我直言,更简洁)用普通循环和条件而不是 filter
编写和 forEach
:
function makeTree(categories, parent) {
let node = {};
for (const c of categories)
if (c.parent == parent)
node[c.id] = makeTree(categories, c.id);
return node;
}
现在它只是一个普通的递归函数,没有高阶函数了。
另外,关于
forEach
特别是回调,它使用了一个完全不必要的 grouping parenthesis在 shorthand arrow function syntax而不是用 block 体正确编写它(因为不需要从 forEach
回调返回任何内容):.forEach(c => {
node[c.id] = makeTree(categories, c.id);
});
关于javascript - 具有高阶函数的递归,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58275042/