【问题标题】:DFS implemtation on an Array of objects in Typescript/JavaScriptTypescript/JavaScript 对象数组中的 DFS 实现
【发布时间】:2017-08-06 08:12:26
【问题描述】:

我有一个类,其中包含这样的键、值和子项

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: Container[], key:string){
  • @marvel308 如果我将容器参数设为数组,我无法递归调用 searchKey() 函数
  • 你不能做另一个函数来接受一个数组并将这个searchKey作为一个实用程序调用吗?

标签: javascript arrays typescript microsoft-distributed-file-system


【解决方案1】:

您的searchKey() 函数当前接受一个Container 并检查它是否与key 匹配。如果失败,它会遍历Containers 的children 数组,并在每个数组上递归调用自己。

如果您只打算使用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() 函数从遍历Containers 的数组开始。它检查每个Container 是否有key 匹配,如果找不到,它会在children 数组上递归调用自己。


当然,还有其他方法可以做到这一点。示例:

  • 两个相互递归的函数;
  • 接受Container | Container[] 参数的单一双重用途函数;
  • 一个简单的 shim,它使用一个虚拟的 Container 对象调用您现有的 searchKey(),该对象的 children 是您想要的数组。

哪个最好取决于您的用例。

希望有所帮助;祝你好运。

【讨论】:

    猜你喜欢
    • 2020-04-12
    • 2019-01-14
    • 2021-02-23
    • 2020-08-04
    • 2019-02-25
    • 2018-04-21
    • 2019-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多