javascript - Typescript/JavaScript 中对象数组中的 DFS 实现

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

我有一个包含键、值和子项的类,如下所示

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()与假人 Containerchildren 的对象是你想要的数组。

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

希望有帮助;祝你好运。

关于javascript - Typescript/JavaScript 中对象数组中的 DFS 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45518864/

相关文章:

arrays - 重新排列一个数组,使 arr[i] 变成 arr[arr[i]] 并增加 O(1) 的额外空间

arrays - 小于限制的最大总和

angular - 范围变量 - 为变量赋值时出错

typescript ///< 引用路径 ="..."> : why doesn't it work for me?

javascript - 调试问题: detect where my focus is with jQuery?

javascript - PHP聊天客户端-服务器通信

javascript - 防止 if 语句中的错误 "is undefined"

带有子路径和导航栏的 Angular 模块

javascript - 如何通过 Date 属性过滤对象数组,仅显示每天最后存储的对象?

javascript - 排序元素折叠和内容重新加载