递归过多
我在 firefox 4 上使用 JS,并收到以下代码的“太多递归错误”:
extractText: function(domObj) {
if (domObj == null) {
return "";
} else {
var acc = "";
if (domObj.nodeType == Node.TEXT_NODE) {
acc += domObj.nodeValue;
}
if (domObj.hasChildNodes()) {
var children = currentObj.childNodes;
for (var i = 0; i < children.length; i++) {
acc += sui.extractText(children[i]);
}
}
return acc;
}
}
};
有人吗?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为这一行:
应该是:
在我看来,您对“currentObj”的引用似乎是从顶部开始,而不是从正在检查的元素下降。当然很难说,因为您没有包含“currentObj”的相关定义或初始化。
I think that this line:
should be:
It looks to me as if your reference to "currentObj" is starting over at the top instead of descending from the element under examination. It's hard to tell of course because you didn't include the relevant definition or initialization of "currentObj".
您还可以尝试迭代方法而不是递归:
该算法使用以下方法实现深度优先搜索仍然必须访问的节点的堆栈。如果堆栈上的第一项是 节点实例。然后对于堆栈上的每个节点:如果它是 Text节点,其值被添加到文本片段数组
tf
中;如果它是一个 元素节点,其子节点以相反的顺序放入堆栈,以便第一个子节点位于堆栈顶部。重复这些步骤直到堆栈为空。最后,使用数组的join
方法将tf
中的文本片段组合在一起。You can also try an iterative approach instead of recursion:
This algorithm implements a depth first search using a stack for the nodes that still must be visited. The first item on the stack is
domObj
if it’s a Node instance. Then for each node on the stack: if it is a Text node, its value is added to the text fragments arraytf
; if it’s an Element node, its child nodes are put on the stack in reverse order so that the first child is on top of the stack. These steps are repeated until the stack is empty. At the end, the text fragments intf
are put together using the array’sjoin
method.