本篇文章给大家带来的内容是关于JavaScript实现DOM树的深度优先遍历和广度优先遍历(代码实例),有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
// 非递归,首次传入的node值为DOM树中的根元素点,即html // 调用:deep(document.documentElement) function deep (node) { var res = []; // 存储访问过的节点 if (node != null) { var nodeList = []; // 存储需要被访问的节点 nodeList.push(node); while (nodeList.length > 0) { var currentNode = nodeList.pop(); // 当前正在被访问的节点 res.push(currentNode); var childrens = currentNode.children; for (var i = childrens.length - 1; i >= 0; i--) { nodeList.push(childrens[i]); } } } return res; } // 使用递归 var res = []; // 存储已经访问过的节点 function deep (node) { if (node != null) { // 该节点存在 res.push(node); // 使用childrens变量存储node.children,提升性能,不使用node.children.length,从而不必在for循环遍历时每次都去获取子元素 for (var i = 0, childrens = node.children; i <h4>广度优先遍历</h4><pre class="brush:php;toolbar:false">// 递归 var res = []; function wide (node) { if (res.indexOf(node) === -1) { res.push(node); // 存入根节点 } var childrens = node.children; for (var i = 0; i 0) { var currentNode = nodeList.shift(0); res.push(currentNode); for (var i = 0, childrens = currentNode.children; i <p>以上就是对javascript实现dom树的深度优先遍历和广度优先遍历(代码实例)的全部介绍,如果您想了解更多有关<a href="http://www.php.cn/course/list/17.html" target="_self">javascript视频教程</a>,请关注php中文网。</p>
以上就是JavaScript实现DOM树的深度优先遍历和广度优先遍历(代码实例)的详细内容,更多请关注php中文网其它相关文章!
Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号