-
Notifications
You must be signed in to change notification settings - Fork 293
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
第 4 题:如何遍历一个dom树 #4
Comments
hello,请问为什么要把i定义在外面? |
外面空气好啊 |
if (item.nodeType === 1) { 这里的判断可以省略吧,毕竟递归之后又会重新判断 |
|
这样效率高,在那本书上看到过这种写法 |
var 的话这个写里面和写外面是一样的把 变量提升 js 没有块级作用域把 |
//尾递归 |
var node,treeWalker = document.createTreeWalker(document.body,NodeFilter.SHOW_ELEMENT)
while(node=treeWalker.nextNode())
console.log(node) |
那是不是应该加一个console.log输出, 是不是就跟上面的console.log输出重复了? |
非递归写法,可以的,很强 |
是的 所以写在外面只是一起定义了变量 更清楚当前作用域定义了哪些变量 |
// 借用一下前面的
function traversal(node) {
if(!node){
console.log(node);
return;
}
const stack = Array.from(node); // 获取的是 HTMLNodes 类数组对象,转成数组
while(stack.length > 0) {
const elem = stack.pop();
if (elem && elem.nodeType === 1) {
console.log(elem.tagName);
const children = elem.children || [];
children.length>0 && stack.push(...children); // 直接进行解构操作
}
}
} |
不满足条件就直接不后续处理了呗,省略条件 traversal 又会执行一遍(根本没什么意义) |
const stack =[...node]; 更喜欢这样,哈哈 |
不是 queue ? |
function traversal(node) {
let stack = [node];
while(stack.length > 0){
const curNode = stack.pop();
if (curNode) {
if (curNode.nodeType === 1) {
console.log(curNode.tagName);
}
const childNodes = [...curNode.childNodes];
stack = stack.concat(childNodes);
}
}
} |
|
The text was updated successfully, but these errors were encountered: