gpt4 book ai didi

javascript - JavaScript 中的递归循环

转载 作者:行者123 更新时间:2023-12-03 12:18:57 25 4
gpt4 key购买 nike

我尝试使用递归循环将某些属性写入 html,但无法使代码工作:(

我有哈希数组,正如您在 Json 中看到的那样。具有以下属性:serno - 序列号、parent_serno - 父级的序列号、name - 属性名称。我想首先写下每个具有“parent_serno == 0”的 hash.name,然后在每个之后我想写下具有“parent_serno = serno(第一个散列)”的散列名称,这是根据将它们分组serno 和parent_serno。

你们能告诉我我做错了什么吗?

 var dataBase = [{"serno": 1, "parent_serno": 0, "name": "Home"},
{"serno": 2, "parent_serno": 0, "name": "Search"},
{"serno": 10, "parent_serno": 2, "name": "Search Payment"},
{"serno": 11, "parent_serno": 2, "name": "Problematic Search Payment"},
{"serno": 12, "parent_serno": 2, "name": "Cash Error"},
{"serno": 13, "parent_serno": 2, "name": "Payment Note"},
{"serno": 89, "parent_serno": 2, "name": "Search Payment By Category"},
{"serno": 131, "parent_serno": 2, "name": "Search Payment New"},
{"serno": 3, "parent_serno": 0, "name": "User Mangement"},
{"serno": 4, "parent_serno": 0, "name": "Service Provider"},
{"serno": 5, "parent_serno": 0, "name": "General"},
{"serno": 88, "parent_serno": 5, "name": "Balance and Financial"},
{"serno": 14, "parent_serno": 5, "name": "My Subagents"},
{"serno": 15, "parent_serno": 5, "name": "My Providers"},
{"serno": 16, "parent_serno": 5, "name": "My Dealers"},
{"serno": 17, "parent_serno": 5, "name": "My Wallets"},
{"serno": 19, "parent_serno": 5, "name": "Accounts"},
{"serno": 45, "parent_serno": 19, "name": "Bank Accounts"},
{"serno": 46, "parent_serno": 19, "name": "Transfers"},
{"serno": 0, "parent_serno": 5, "name": "My Statements"},
{"serno": 47, "parent_serno": 20, "name": "My Terminals"}];

var funkcia = function(parent) {
for (var i=0, i < dataBase.length, i++){
if (dataBase[i].parent_serno == parent){
document.write(dataBase[i].name);
parent = dataBase[i].serno;
funkcia(parent);
};
};
};

funkcia(0);

最佳答案

 parent = dataBase[i].serno;
funkcia(parent);

这是你的问题。您正在更改 parent 变量,但随后让 for 循环继续运行,现在正在搜索错误的 parent

要么使用不同的变量:

function funkcia(parent) {
for (var i=0; i < dataBase.length; i++){
if (dataBase[i].parent_serno == parent){
document.write(dataBase[i].name);
var new_parent = dataBase[i].serno;
funkcia(new_parent);
}
}
}

或者根本没有:

function funkcia(parent) {
for (var i=0; i < dataBase.length; i++){
if (dataBase[i].parent_serno == parent){
document.write(dataBase[i].name);
funkcia(dataBase[i].serno);
}
}
}

关于javascript - JavaScript 中的递归循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24528918/

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