[
{
"id": 1,
"name": "sys",
"title": "系统设置",
"type": 1,
"status": 1,
"condition": "",
"pid": 0,
"level": 0,
"sort": 7,
"icon": "fa-gear",
"children": [
{
"id": 11,
"name": "conf/lst",
"title": "配置列表",
"type": 1,
"status": 1,
"condition": "",
"pid": 1,
"level": 1,
"sort": 50,
"icon": null,
"children": [
{
"id": 12,
"name": "conf/add",
"title": "添加配置",
"type": 1,
"status": 1,
"condition": "",
"pid": 11,
"level": 2,
"sort": 50,
"icon": null,
"children": []
},
{
"id": 13,
"name": "conf/del",
"title": "配置删除",
"type": 1,
"status": 1,
"condition": "",
"pid": 11,
"level": 2,
"sort": 50,
"icon": null,
"children": []
},
{
"id": 14,
"name": "conf/edit",
"title": "配置编辑",
"type": 1,
"status": 1,
"condition": "",
"pid": 11,
"level": 2,
"sort": 50,
"icon": null,
"children": []
}
]
},
{
"id": 9,
"name": "conf/conf",
"title": "配置项",
"type": 1,
"status": 1,
"condition": "",
"pid": 1,
"level": 1,
"sort": 50,
"icon": null,
"children": []
}
]
},
{
"id": 15,
"name": "admin",
"title": "管理员",
"type": 1,
"status": 1,
"condition": "",
"pid": 0,
"level": 0,
"sort": 50,
"icon": "fa-user",
"children": [
{
"id": 16,
"name": "admin/lst",
"title": "管理员列表",
"type": 1,
"status": 1,
"condition": "",
"pid": 15,
"level": 1,
"sort": 50,
"icon": null,
},
{
"id": 27,
"name": "authrule/lst",
"title": "权限列表",
"type": 1,
"status": 1,
"condition": "",
"pid": 15,
"level": 1,
"sort": 50,
"icon": null,
},
{
"id": 30,
"name": "authgroup/lst",
"title": "用户组",
"type": 1,
"status": 1,
"condition": "",
"pid": 15,
"level": 1,
"sort": 50,
"icon": null,
}
]
}
]
The json above is a multi-dimensional array. I want to use js for loop to output the array under children, but I don’t know why it cannot be output and no error is reported.
$.ajax({
type: "get",
url: "/admin/index/menu",
async: true,
dataType: 'json',
success: function(res) {
for(var i = 0; i < res.length; i++) {
console.log(res[i].children); //这个能输出
for (var a=0;a<res[i].children;a++) {
console.log(res[i].children[a]); //这个不能输出,也没有报错
}
}
}
})
Excuse me, what’s wrong?
女神的闺蜜爱上我2017-07-05 10:41:52
$.ajax({
type: "get",
url: "/admin/index/menu",
async: true,
dataType: 'json',
success: function(res) {
for(var i = 0; i < res.length; i++) {
console.log(res[i].children);
for (var a = 0; a < res[i].children.length; a++) { // <-- 此处少了.length,数字和对象比较大小,结果为false,第二个条件一次也满足不了
console.log(res[i].children[a]);
}
}
}
}
怪我咯2017-07-05 10:41:52
Although I’m late, I think I can add something else
Generally, I personally prefer to use foreach
traversal, in JS (take the code in this example as an example)
res.forEach(r => {
r.children.forEach(c => {
// do something
});
});
The arrow function of es6 is used above. If you want to write it in es5, just change it to function expression
学习ing2017-07-05 10:41:52
This should be a recursion. It is recommended to understand the knowledge of recursion
Recursively traverse nodes