我有以下用JavaScript编写的递归函数:
function getNestedChildren(arr, parent) {
let out = [];
arr.forEach(function (item) {
if (item.Parent == parent) {
let children = getNestedChildren(arr, item.ID);
if (children.length) {
item.children = children;
}
out.push(item);
}
});
return out
} // getNestedChildren
这里的工作示例:https://jsfiddle.net/fp1zvf0h/7/
在VS Code中重构为TypeScript,如:
private getNestedChildren(arr:object[], parent:number):object[] {
let out:object[];
arr.forEach((item:{ID:number, Parent:number, children:{}}) => {
if (item.Parent === parent) {
let children:object[] = getNestedChildren(arr, item.ID);
if (children.length) {
item.children = children;
}
out.push(item);
}
});
return out;
} // getNestedChildren
我在行上收到了编译错误Cannot find name 'getNestedChildren'
:
let children:object[] = getNestedChildren(arr, item.ID);
我错过了什么?
答案 0 :(得分:4)
通过包含单词private
,看起来这是一个对象方法,在这种情况下你应该调用this.getNestedChildren(arr, item.ID);