首页 > 基础资料 博客日记

Javascript递归

2023-07-24 19:28:40基础资料围观219

这篇文章介绍了Javascript递归,分享给大家做个参考,收藏Java资料网收获更多编程知识

window.onload = function () {

    var data = [{ "id": "01", "parentId": "0", "name": "后端编程语言" },
    { "id": "02", "parentId": "0", "name": "前端编程语言" },
    { "id": "03", "parentId": "0", "name": "嵌入式开发" },
    { "id": "0101", "parentId": "01", "name": ".NET" },
    { "id": "010101", "parentId": "0101", "name": "C#语言" },
    { "id": "010102", "parentId": "0101", "name": "F#语言" },
    { "id": "01010102", "parentId": "010101", "name": "C#2.0" },
    { "id": "01010101", "parentId": "010101", "name": "C#1.0" },
    { "id": "0102", "parentId": "01", "name": "Java" },
    { "id": "010201", "parentId": "03", "name": "Android" },
    { "id": "0102012323", "parentId": "0103", "name": "G0.1" },
    { "id": "0103", "parentId": "01", "name": "Go" },
    { "id": "0201", "parentId": "02", "name": "Javascript" },
    { "id": "0202", "parentId": "02", "name": "Typescript" }
];



  console.log("============从上往下查找================")
    let resultArray = [];
    let getChilds = function (pid, parent) {
        let childs = [];
        for (const child of data) {
            if (child.parentId === pid) {
                childs.push(child);
            }
        }
        if (childs.length <= 0) {
            if (parent) {
                delete parent.children;
            }
            return;
        }

        for (const c of childs) {
            let v;
            if (!parent) {
                v = { lable: c.name, children: [] };
                resultArray.push(v);
            } else {
                v = { lable: c.name, children: [] };
                parent.children.push(v);
            }
            getChilds(c.id, v);
        }

    };

    // getChilds("0");
    // console.log(resultArray)

    
    console.log("============从下往上查找================")
    let rootReusltArray = [];
    let getRoot = function (id) {
        if (id == '0') {
            return;
        };
        for (const item of data) {
            if (item.id === id) {
                rootReusltArray.push(item.name);
                getRoot(item.parentId);
                return;
            }
        }
    }

    getRoot('010101');
    console.log(rootReusltArray.reverse())
}

 


文章来源:https://www.cnblogs.com/gaobing/p/16493481.html
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐

标签云