在項目中遇到的問題-- 一個級聯題,知道答案id 后將每一級的選項展示出來
例如 級聯題的 json 數據是
[ { name: '北京', id: 1, children:[ { name: '朝陽', id: 3, children: [ { name: '北京站', id: 9 } ] }, { name: '海淀', id: 4, children: [ { name: '中關村', id: 10 } ] } ] }, { name:'河北', id:2, children:[ { name: '張家口', id: 5, children:[ { name: '宣化', id: 7 } ] }, { name: '石家庄', id: 6, children: [ { name: '無極', id: 8 } ] } ] } ]
現在知道 獲取到的最后一級答案 id 是10 將所有選中的菜單計算出來
function getcascade (opts,opt,path) { if (path===undefined) { path = [] } for(var i=0;i<opts.length;i++){ var temPath = path.concat() temPath.push(opts[i].name) if (opt == opts[i].id){ return temPath } if (opts[i].children){ var findResult = getcascade(opts[i].children,opt,temPath) if (findResult){ return findResult } } } } let list = getcascade(json,10) console.log(list)
得到結果
[ '北京', '海淀', '中關村' ]
該遞歸方法中用到了 數組的concat 方法 該方法連接兩個數組 不改變原數組,
在循環調用當中 遇到return 后直接返回結果 跳出函數。