zoukankan      html  css  js  c++  java
  • 对象的广度遍历和深度遍历

    数组的遍历有多种方法,也有多种形式。

    对象的遍历除了for in,当对象数据多层嵌套时候,遍历的方式又可以分深度优先遍历和广度优先遍历。那么怎么实现呢?

     1 <!DOCTYPE html>
     2 <html lang="en">
     3 
     4 <head>
     5     <meta charset="UTF-8">
     6     <meta http-equiv="X-UA-Compatible" content="IE=edge">
     7     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     8     <title>对象数据的深度遍历和广度遍历</title>
     9 </head>
    10 
    11 <body>
    12     <script>
    13         var obj = {
    14             a: {
    15                 b: {
    16                     d: {
    17                         f: 22
    18                     }
    19                 },
    20                 c: {
    21                     e: {
    22                         g: 33
    23                     }
    24                 }
    25             }
    26         }
    27 
    28 
    29 
    30         let BFSARR = [];
    31         // Breadth First Search 
    32         function BFS(obj) {
    33             let undo = [];
    34             if (obj === null || typeof obj !== "object") return;
    35             undo.unshift(obj);
    36             while (undo.length) {
    37                 let item = undo.shift();
    38                 Object.entries(item).map(([key, val]) => {
    39                     BFSARR.push(key)
    40                     undo.push(val);
    41                 });
    42             };
    43             return BFSARR;
    44         }
    45         console.log(BFS(obj));
    46 
    47         let DFSARR = []
    48         // Depth First Search
    49         function DFS(obj) {
    50             newObj = obj
    51             if (obj === null || typeof obj !== "object") return;
    52             Object.entries(obj).map(([k, v], index) => {
    53                 DFSARR.push(k);
    54                 if (typeof v === "object") {
    55                     DFS(v)
    56                 }
    57             })
    58             return DFSARR;
    59         }
    60         console.log(DFS(obj), 'newObj');
    61     </script>
    62 </body>
    63 
    64 </html>

    对象的数据遍历是重点。

    我站在山顶看风景!下面是我的家乡!
  • 相关阅读:
    怎样把Maven项目共享为传统Web项目
    伸冤人
    Maven依赖
    Maven常用插件参数
    Maven默认周期与插件
    MySQL Connector_J_5.1.34_2014.10
    MyEclipse2015对Javascript自动提示的终极支持
    Struts Convention Plugin 流程 (2.1.6+)
    Maven,预加载资源文件
    Myeclipse2014 自带的报表功能 与 Eclipse BIRT
  • 原文地址:https://www.cnblogs.com/zhensg123/p/14876785.html
Copyright © 2011-2022 走看看