首页 > Web开发 > 详细

JS - 递归实现无限分类

时间:2020-05-07 21:58:15      阅读:62      评论:0      收藏:0      [点我收藏+]
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>无限分类</title>
  </head>
  <body>
    <script>
      window.onload = function () {
        console.log(deeploop());
      };

      /**
       *   根据 id 查询到数据并将数据存储到数组 返回
       */
      var findById = function (id) {
        let child = [];
        arr.forEach((value) => {
          if (value.pid == id) {
            child.push(value);
          }
        });
        return child;
      };

      /**
       *   递归查询  到数据并将数据存储到数组 返回
       */
      var deeploop = function (id) {
        let dataArr = findById(id);
        if (dataArr.length <= 0) {
          return null;
        } else {
          dataArr.forEach((value) => {
            if (deeploop(value.id) != null) {
              value["children"] = deeploop(value.id);
            }
          });
        }
        return dataArr;
      };

      /**
       *   每一个分类都有记录它的父级id (pid 意为 parent id)
       *   当为顶级分类时,它的父级id为0
       */
      var arr = [
        { id: 1, name: "计算机专业", pid: 0 },
        { id: 2, name: "软件专业", pid: 1 },
        { id: 3, name: "前端", pid: 2 },
        { id: 33, name: "html", pid: 3 },
        { id: 34, name: "css", pid: 3 },
        { id: 4, name: "后端", pid: 2 },
        { id: 41, name: "php", pid: 4 },
        { id: 42, name: "java", pid: 4 },
        { id: 5, name: "动漫专业", pid: 0 },
        { id: 51, name: "2d动漫", pid: 5 },
        { id: 511, name: "插画设计", pid: 51 },
        { id: 52, name: "3d动漫", pid: 5 },
      ];
    </script>
  </body>
</html>

 

JS - 递归实现无限分类

原文:https://www.cnblogs.com/500m/p/12845651.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!