填充数组递归遍历DOM树 [英] Fill an array recursively walking a DOM tree

查看:109
本文介绍了填充数组递归遍历DOM树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我走一个通用的树从一个节点到他所有的孩子递归来填充字符串数组。在从到叶节点匹配每个节点实际上,插入在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树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆