// 非常nice 的递归方法: for (let i = 0, len = menuList.length; i < len; i++) { console.log(Number(menuList[i].id), Number(obj.id)) if (Number(menuList[i].id) === Number(obj.id)) { console.log(menuList[i], ‘--------------------9089899878979’) return menuList[i]; } if (menuList[i].children) { this.findTreeOfObj(menuList[i].children, obj); } }
结果:走了打印的结果,却无法retrun
改写成:
let result = {}; menuList.forEach(item => { const loop = data => { if (Number(data.id) === Number(obj.id)) { result = data; return result; } let child = data.children; if (child) { for (let i = 0; i < child.length; i++) { loop(child[i]) } } } loop(item); }) return result;
结果:成功,