// 递归 函数自己调自己 节省代码避免死循环
// 如果一个函数在内部自己调用自己本身,那么这个函数就是递归函数
// 递归的作用效果和循环一样, (性能比循环低)
let rootList = [ // 使用递归实现平级 转 树形
{ id: 1, parent: null, text: "菜单1" },
{ id: 11, parent: 1, text: "菜单1-1" },
{ id: 12, parent: 1, text: "菜单1-2" },
{ id: 2, parent: null, text: "菜单2" },
{ id: 21, parent: 2, text: "菜单2-1" },
{ id: 23, parent: 2, text: "菜单2-2" },
{ id: 3, parent: null, text: "菜单3" },
{ id: 31, parent: 3, text: "菜单3-1" },
{ id: 33, parent: 3, text: "菜单3-2" },
{ id: 4, parent: null, text: "菜单3" },
// ...
]
function getTreeList(rootList, id, list) {
for (let item of rootList) {
if (item.parent == id) {
list.push(item)
}
// console.log(list,'一级'); // [{},{}] 处理一级菜单
}
for (let i of list) {
// list 是上面的一级的
i.child = [];
getTreeList(rootList, i.id, i.child)
if(i.child.length == 0) { // 如果下面的子级 为空去除掉
delete i.child
}
}
return list
// console.log(list,'多级');
}
const res = getTreeList(rootList, null, [])
console.log(res, '结构+');
// 追加到 页面上
function addEmement(arr, father) { // arr 数据 父盒子
// 便利数组 生成div > p添加至父元素中
for(let i = 0; i< arr.length; i++){
console.log(arr[i]);
// 1 创建空标签
let div = document.createElement('div')
// 2 设置内容
div.innerHTML = `<p>${arr[i].text || null}`
// 3 添加父盒子
father.appendChild(div)
// 如果还有子级菜单 则继续循环 判断有子级
if(arr[i].child){
addEmement(arr[i].child , div)
}
}
}
let menu = document.querySelector('.menu')
addEmement(res,menu)
大佬请走开!! 如果有错误或者不严谨的地方,请留言备注,十分感谢,对作者也是一种鼓励。