JavaScript递归计算DOM节点距根节点深度返回undefined问题求解
问题根因
递归调用未向上传递返回值是导致最终结果为undefined的核心原因:你写的findDepth函数仅在递归终止的else分支(父节点为comment-0)中返回了深度值,但是在触发递归的if分支里,仅执行了findDepth(el.parentNode, depth),没有将该调用的计算结果返回给上层调用者,因此除了最内层的终止层外,所有外层递归调用都没有返回值,最终外层拿到的结果自然是undefined。
修复代码
仅需要在递归调用的位置补充return即可,修改后的函数如下:
const findDepth = (el, depth) => { depth++; console.log(el.id, el.parentNode.id); console.log(depth); if(el.parentNode.id !== 'comment-0'){ // 新增return,将递归计算结果向上传递 return findDepth(el.parentNode, depth); }else { return depth; } };
运行验证
修改后执行遍历逻辑,会输出符合预期的深度结果:
- el: comment-2598 1
- el: comment-2599 2
- el: comment-2615 3
- el: comment-2604 2
- el: comment-2616 3
拓展:非递归实现方案
如果不想使用递归,也可以用循环实现相同逻辑,代码更简洁且不会有递归栈溢出风险:
const findDepth = (el) => { let depth = 0; let currentNode = el; // 向上遍历直到碰到根节点comment-0 while(currentNode.parentNode.id !== 'comment-0') { depth++; currentNode = currentNode.parentNode; } return depth + 1; }
内容的提问来源于stack exchange,提问作者Gary Thompson
相关产品推荐
相关产品推荐

