遍历dom
遍历的两种实现:
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.实现拷贝