我有一个包含键、值和子项的类,如下所示
class Container{
key: string,
value: string,
children: Container[]
}
function searchKey(container: Container, key:string){
if (container.key == key) {
return container;
}
else if (container.children.length>0){
for (let child of container.children) {
let found = searchKey(child, key);
if (found != null) {
return found;
}
}
}
return null;
}
我将提供给 searchKey() 函数的输入将是一个包含深层对象的数组,我想获取所提供的键参数的值。但当前的 searchKey() 函数不接受数组。如何使其使用数组作为输入?
最佳答案
您的searchKey()
函数当前接受单个 Container
并检查它是否与 key
匹配。如果失败,它将迭代 children
Container
数组s 并在每个上递归调用自身。
如果您只想使用 Container
的数组来调用该函数并且永远不需要传入一个 Container
,然后你可以像这样将函数从里到外翻转:
function searchKey(containers: Container[], key: string): Container | null {
if (containers.length > 0) {
for (let container of containers) {
if (container.key == key) {
return container;
} else {
let found = searchKey(container.children, key);
if (found != null) {
return found;
}
}
}
}
return null;
}
(我尝试使上述函数保持与原始函数相同的风格。)
这个searchKey()
函数首先迭代 Container
的数组s。它检查每个 Container
对于key
匹配,如果没有找到,它会在 children
上递归调用自身数组。
当然,还有其他方法可以做到这一点。示例:
- 两个相互递归的函数;
- 一个单一的双用途函数,接受
Container | Container[]
论据; - 一个简单的垫片,它调用您现有的
searchKey()
与假人Container
其children
的对象是你想要的数组。
哪一个最好取决于您的用例。
希望有帮助;祝你好运。
关于javascript - Typescript/JavaScript 中对象数组中的 DFS 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45518864/