[
{
"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?
a<res[i].children
->a<res[i].children.length
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)The arrow function of es6 is used above. If you want to write it in es5, just change it to function expression
This should be a recursion. It is recommended to understand the knowledge of recursion
Recursively traverse nodes