我尝试使用递归循环将某些属性写入html,但不能使代码工作:(
我在Json中看到了哈希数组。具有以下属性:serno - 序列号,parent_serno - 父序列号,名称 - 属性的名称。我想先写下每个hash.name,其中包含" parent_serno == 0"然后在每一个之后我想要写出具有" 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);
答案 0 :(得分:1)
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);
}
}
}