首页 > 其他 > 详细

遍历dom

时间:2019-07-18 16:04:56      阅读:96      评论:0      收藏:0      [点我收藏+]

遍历的两种实现:
1.深度优先遍历:

    const seekDFS=function(rootNode){
        let nodes=[];
        const search=(rootNode)=>{
            if(rootNode.nodeType===1){
                nodes.push(rootNode);
                let children=rootNode.childNodes;
                if(children){
                    for(let i=0;i<children.length;i++){
                        if(children[i].nodeType==1){
                            search(children[i]);
                        }
                    }
                }
            }
        }
        search(rootNode);
        return nodes;
    }

2.广度优先遍历:

    const seekBFS=function(rootNode){
        let stack=[];
        let nodes=[];
        if(rootNode.nodeType==1){
            stack.push(rootNode);
            while(stack.length){
                let item=stack.pop();
                nodes.push(item);
                let children=item.childNodes;
                for(let i=0;i<children.length;i++){
                    if(children[i].nodeType==1){
                        stack.push(children[i]);
                    }
                }
            }
        }
        return nodes;
    }

这两种算法在的意义:
1.遍历dom节点,框架中常用到;
2.实现拷贝

遍历dom

原文:https://www.cnblogs.com/maoBable/p/11207794.html

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