gpt4 book ai didi

javascript - 编写递归 JavaScript 算法来查找特定对象类型

转载 作者:行者123 更新时间:2023-11-28 17:33:18 26 4
gpt4 key购买 nike

本质上,我正在测试一个层次结构 TreeView 数据集,以查看是否存在任何被视为 Host 节点的对象;也就是说,它只有属性 HostIDHostName

如果我只找到一个 Host 节点,我会返回 true - 就完成了。

但是,我在下面的递归例程中没有获得准确的 true/false 返回值。即我有时会得到不准确的错误返回值。

hasChildHosts_2(tree: any) {
if (tree.subs !== null && tree.subs.length > 0) {
for (var i = 0; i < tree.subs.length; i++) {
if (tree.subs[i].HostID != null && tree.subs[i].HostName != null) {
return true;
}
if (tree.subs[i].subs !== undefined) {
this.hasChildHosts_2(tree.subs[i]);
}
}
return false;
} else {
return false;
}

}

一个小样本集如下:一个 Location 节点包含一个 subs 数组 - 其中包含一个 Location 节点和两个 Host 节点。当然,我总是通过 LocationName 属性知道位置,并通过 HostID 属性知道主机:

{ "UID":2,"GUID":"","LocationName":"Bergen County","ParentLocation":null, "subs":[ {"UID":42,"GUID":"","LocationName":"yy","Description":"","subs":[ {"UID":3,"GUID":"","LocationName":"Essex County","ParentLocation":null} {"HostID":100,"HostName":"MYHOST100","HostIP":"10.1.1.12"},
{"HostID":200,"HostName":"MYHOST200","HostIP":"10.1.1.19"} ] ] } }

请检查准确性。欢迎提供反馈。

最佳答案

我已经在示例代码笔上实现了您的代码。正如评论所指出的,您需要返回递归函数的结果。此外,该树是无效的 JSON,我已修复它:

var globalTree = {
UID: 2,
GUID: "",
LocationName: "Bergen County",
ParentLocation: null,
subs: [{
UID: 42,
GUID: "",
LocationName: "yy",
Description: "",
subs: [{
UID: 3,
GUID: "",
LocationName: "Essex County",
ParentLocation: null
},
{
HostID: 100,
HostName: "MYHOST100",
HostIP: "10.1.1.12"
},
{
HostID: 200,
HostName: "MYHOST200",
HostIP: "10.1.1.19"
}
]
}]
};

var hasChildHosts_2 = function(tree) {
if (tree.subs !== null && tree.subs.length > 0) {
for (var i = 0; i < tree.subs.length; i++) {
if (tree.subs[i].HostID != null && tree.subs[i].HostName != null) {
return true;
}
if (tree.subs[i].subs !== undefined) {
return hasChildHosts_2(tree.subs[i]);
}
}
return false;
} else {
return false;
}
};
console.log("result: " + hasChildHosts_2(globalTree));

关于javascript - 编写递归 JavaScript 算法来查找特定对象类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49805155/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com