继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

【九月打卡】第7天 深度 / 广度优先遍历 DOM 树

ICHAYA
关注TA
已关注
手记 40
粉丝 15
获赞 378

课程名称2周刷完100道前端优质面试真题
课程章节:第8章 前端面试技能拼图6: 编写高质量代码 - 正确,完整,清晰,鲁棒
主讲老师双越
课程内容
今天学习的内容包括:
8-8 深度优先遍历一个DOM树
8-9 广度优先遍历一个DOM树
8-10 【连环问】深度优先遍历可以不用递归吗

课程收获
大概复述一下学的内容。

深度优先遍历:
div>p>hello >b>world >img > 注释 > ul>li>a >li>b
广度优先遍历:
div> p>img>注释>ul > hello>b>li>li > world>a>b

node 和 element 区别
childNodes:任何元素的节点。HtmlElement、文本(含换行)、注释
chilldren:HtmlElement

打印节点

节点分不同类型打印。

const visitNode = (node) => {
	if (node instanceof Comment) {
    console.log("注释", node.textContent);
  } else if (node instanceof Text) {
    // 去除换行符、空格
    const t = node.textContent?.trim();
    if (t) {
      console.log("文本", t);
    } 
  } else if (node instanceof HTMLElement) {
    console.log("HTMLElement", `<${node.tagName.toLowerCase()}>`);
  }
}

深度优先遍历递归实现

读取当前节点,并依次读取当前深度遍历后的子节点。

  const dfs = (node) => {
    if (node) {
      visitNode(node);
      if (node.childNodes.length) {
        node.childNodes.forEach(element => dfs(element));
      }
    }
  }

深度优先遍历栈实现

访问栈顶元素,并把子元素全部逆序入栈。

    const dfs1 = (node) => {
      let stack = [];
      stack.push(node);
      while(stack.length > 0) {
        const curNode = stack.pop();
        if (curNode == null) {
          break;
        }
        visitNode(curNode);
        if (curNode.childNodes.length) {
          Array.from(curNode.childNodes).reverse().forEach((element) => stack.push(element));
        }
      }
    };

广度优先遍历

利用队列。 访问队头,并把队头的子元素全部入队。直到整个队列处理完。

    const bfs = (node) => {
      let queue = [];
      queue.unshift(node);
      while(queue.length > 0) {
        const curNode = queue.pop();
        if (curNode == null) {
          break;
        }
        visitNode(curNode);
        if (curNode.childNodes.length) {
          curNode.childNodes.forEach((element) => queue.unshift(element));
        }
      }
    };

以上,结束。

打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP