问题描述
我有我走一个通用的树从一个节点到他所有的孩子递归来填充字符串数组。在从到叶节点匹配每个节点实际上,插入在DOM树中的字符串。
我知道这是一个微不足道的问题,但我没能解决。
这是code,我写道:
I have to fill an array of strings as I walk a generic tree recursively from one node to all his children. In practice at each node that match from a node to a leaf, insert a string in the DOM tree.I know it is a trivial problem but I could not solve.This is the code that I wrote:
function operationsToInsert(node) {
var operations = [];
operationsToInsertRec(node, operations);
return operations;
}
function operationsToInsertRec(node, operations) {
var childNodes = node.childNodes;
operations.push("i(" + node.nodeName + ") ");
for(var i = 0; i < childNodes.length; i++) {
operationsToInsertRec(childNodes[i], operations);
operations.push("i(" + childNodes[i].nodeName + ")");
}
}
但有以下错误:
未捕获类型错误:无法读取酒店在行 operations.push的不确定
推(插入(+ node.nodeName +));
Uncaught TypeError: Cannot read property 'push' of undefined at line operations.push("insert(" + node.nodeName + ") ");
我该如何解决?
谢谢
How can I fix?Thanks
推荐答案
下面是一个使用得心应手Array.prototype.reduce功能使用技巧,让它在阵列喜欢工作走一棵树的方式:
Here's a way to walk a tree using the handy Array.prototype.reduce function using a trick that lets it work on array-likes:
function flatten(ops, n) {
ops.push("i(" + n.nodeName + ") ");
if (n.childNodes && n.childNodes.length) {
[].reduce.call(n.childNodes, flatten, ops);
}
return ops;
}
var node = document.getElementById("start_here");
var ops = [node].reduce(flatten, []);
这篇关于填充数组递归遍历DOM树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!