一个嵌套层级递归的用法案例
let menus = [{ code: 1, name: '山西省', children: [ { code: 2, name: '朔州市', children: [ { code: 5, name: '朔城区' }, { code: 8, name: '山阴' } ] }, { code: 3, name: '大同市', children: [ { code: 6, name: '云冈' } ] }, { code: 4, name: '太原市', children: [ { code: 7, name: '小店区' }, { code: 10, name: '迎泽区' } ] } ] }] function searchCode(list, name) { for (let item of list.values()) { if (item.name == name) { return item.code } else if (item.children) { let result = searchCode(item.children, name) if (result) return result } } } let res = searchCode(menus, '云冈') console.log(res) // 6
小结:
类似于这种层级嵌套的数据结构,如果想找到某一个值,则需要用到递归的思想;
同时,需要注意的是子级的数据需要返回,见红色部分。