最近我参加了前端工程师职位的面试。在电话面试中,我被问到以下问题:给定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);
}
.childNodes
集合没有indexOf()
方法,我猜想这会对你造成很大的不利影响。 - Blue Skies