function traverseTree (tree, cb, isNodeFirst) {
if (isNodeFirst) {
for (let i = 0; i < tree.length; i++) {
cb(tree[i], i, tree)
if (tree[i].children && tree[i].children.length > 0) {
traverseTree(tree[i].children, cb)
}
}
} else {
for (let i = 0; i < tree.length; i++) {
if (tree[i].children && tree[i].children.length > 0) {
traverseTree(tree[i].children, cb)
}
cb(tree[i], i, tree)
}
}
}
1
breezeFP 2021-06-22 17:15:17 +08:00
function traverseTree(tree, cb, isNodeFirst) {
for (let i = 0; i < tree.length; i++) { if(isNodeFirst) { cb(tree[i], i, tree) } if (tree[i].children && tree[i].children.length > 0) { traverseTree(tree[i].children, cb) } if(!isNodeFirst) { cb(tree[i], i, tree) } } } |
3
powerfj 2021-06-22 17:44:45 +08:00
@waiaan traverseTree(tree[i].children, cb) 这个递归调用, 是不是漏了 isNodeFirst 的参数
|
5
autoxbc 2021-06-23 00:51:03 +08:00
用 xpath 可以一次性获取全部节点,不用递归查找
const arr = []; for( let result = document.evaluate('//node()', document ) , next ; next = result.iterateNext() ; arr.push(next) ); console.log(arr); |