数组的遍历有多种方法,也有多种形式。
对象的遍历除了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>
对象的数据遍历是重点。