首页 > 其他 > 详细

对象的广度遍历和深度遍历

时间:2021-06-12 00:40:48      阅读:26      评论:0      收藏:0      [点我收藏+]

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

对象的遍历除了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>

对象的数据遍历是重点。

对象的广度遍历和深度遍历

原文:https://www.cnblogs.com/zhensg123/p/14876785.html

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