javascript - js 多維數組的問題
問題描述
[ {'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, }] }]
上面的json是多維數組,我想用js for循環把children下面的數組輸出,但不知道為什么輸出不了,也沒報錯.
$.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]); //這個不能輸出,也沒有報錯 }} }})
請問是哪里錯了?
問題解答
回答1:$.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]); }} }}回答2:
a<res[i].children -> a<res[i].children.length
回答3:雖然來晚了,但是我覺得還是可以補充一下
一般我個人比較喜歡使用 foreach 遍歷,在 JS 里是(以此例中的代碼為例)
res.forEach(r => { r.children.forEach(c => {// do something });});
上面用了es6的箭頭函數,如果要在 es5 中寫,直接換成 function 表達式就好
回答4:這里應該是要做個遞歸,推薦了解下遞歸知識遞歸遍歷節點
相關文章:
1. 小程序怎么加外鏈,語句怎么寫!求救新手,開文檔沒發現2. javascript - 在 vue里面用import引入js文件,結果為undefined3. javascript - vue-resource中如何設置全局的timeout?4. html5和Flash對抗是什么情況?5. 前端 - node vue webpack項目文件結構6. Java反射問題:為什么android.os.Message的recycleUnchecked方法不能通過反射獲取到?7. php如何獲取訪問者路由器的mac地址8. 多選框寫進數據庫怎么寫9. mysql主從 - 請教下mysql 主動-被動模式的雙主配置 和 主從配置在應用上有什么區別?10. thinkPHP5中獲取數據庫數據后默認選中下拉框的值,傳遞到后臺消失不見。有圖有代碼,希望有人幫忙
