gpt4 book ai didi

javascript - DOM树遍历

转载 作者:行者123 更新时间:2023-12-02 23:38:30 24 4
gpt4 key购买 nike

我最近面试了一个前端工程师职位。对于我的手机屏幕,我提出了以下问题:给定 DOM 树中的一个节点,从相同的 DOM 树中查找相同位置的节点。为清楚起见,请参见下图。

 A         B

O O
|\ |\
O O O O
/|\ /|\
O O O O O O
\ \
O O

这是我的解决方案,我想知道我可以做些什么来改进/优化它。

var rootA, rootB;

function findNodeB(nodeA) {
// Variable to store path up the DOM tree
var travelPath = [];

// Method to travel up the DOM tree and store path to exact node
var establishPath = function(travelNode) {
// If we have reached the top level node we want to return
// otherwise we travel up another level on the tree
if (travelNode === rootA) {
return;
} else {
establishPath(travelNode.parentNode);
}

// We store the index of current child in our path
var index = travelNode.parentNode.childNodes.indexOf(travelNode);
travelPath.push(index);
}

var traverseTree = function(bTreeNode, path) {
if(path.length === 0) {
return bTreeNode;
} else {
traverseTree(bTreeNode.childNodes[path.pop()], path);
}
}

establishPath(rootB, nodeA);

return traverseTree(rootB, travelPath);
}


最佳答案

由于至少 Axel 对迭代解决方案表现出了兴趣,所以它是:

给定两棵具有相同结构的树,以及第一棵树中的指定节点,请在结构中找到第二棵树中具有相同位置的节点。

如果我们没有关于两棵树的其他信息,则每个节点的位置可以表征为从根节点开始的路径,其中路径中的每个步骤都被指定为 childNode 数组的索引。

function indexOf(arrLike, target) {
return Array.prototype.indexOf.call(arrLike, target);
}

// Given a node and a tree, extract the nodes path
function getPath(root, target) {
var current = target;
var path = [];
while(current !== root) {
path.unshift(indexOf(current.parentNode.childNodes, current));
current = current.parentNode;
}
return path;
}

// Given a tree and a path, let's locate a node
function locateNodeFromPath(root, path) {
var current = root;
for(var i = 0, len = path.length; i < len; i++) {
current = current.childNodes[path[i]];
}
return current;
}

function getDoppleganger(rootA, rootB, target) {
return locateNodeFromPath(rootB, getPath(rootA, target));
}

编辑:正如蓝天观察到的,childNodes 没有 .indexOf()。使用 Array.prototype.indexOf.call() 更新

关于javascript - DOM树遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19779438/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com