我怎样才能使这个递归?

时间:2013-12-17 16:39:08

标签: javascript jquery recursion multidimensional-array

包括2d数组的声明,如何进行以下递归?我希望它迭代直到没有“children()”。

    self.buildRelationships = function () {
        relationships = [];
        relationships[0] = [];
        relationships[1] = [];
        relationships[2] = [];
        relationships[3] = [];
        relationships[0][0] = self.name();
        $.each(self.children(), function(i, child) {
            relationships[1][i] = child.name();
            $.each(child.children(), function (j, grandchild) {
                relationships[2][j] = grandchild.name();
                $.each(grandchild.children(), function (k, greatgrandchild) {
                    relationships[3][k] = greatgrandchild.name();
                })
            })
        })
    }

目标的可视化

鉴于此数据:

  • 我!
    • 鲍勃
      • 詹姆斯
        • 戴尔
      • 史蒂夫
    • 比尔
      • 佛瑞德
        • 欧文
        • 帕特里克

.children()仅返回直接子项:

Bob.children()将返回“James”和“Steve”。

我!.children()将返回“Bob”和“Bill”。

接受的答案将创建如下所示的数据:

relationships[0] = "Me!" //this will always have a length of only 1
relationships[1] = "Bob", "Bill"
relationships[2] = "James", "Steve", "Fred"
relationships[3] = "Dale", "Owen", "Patrick"

3 个答案:

答案 0 :(得分:4)

self.buildRelationships = function () {
        relationships = [];
        relationships[0] = [];
        relationships[1] = [];
        relationships[2] = [];
        relationships[3] = [];
        relationships[0][0] = self.name();

        var recursive = function(level) {

            return function(i, child) {
               relationships[level] = relationships[level] || [];

               relationships[level].push(child.name());
               $.each(child.children(), recursive(level + 1));
            }
        }

        $.each(self.children(), recursive(1));
    }

答案 1 :(得分:1)

以下是我如何处理它:

self.buildRelationships = function () {
    var relationships = [];
    addToLevel(self, 0);
    return relationships;

    function addToLevel(node, levelIndex) {
        $.each(node.children(), function (i, child) {
            if (relationships.length <= levelIndex) { relationships.push([]) }
            relationships[levelIndex].push(child.name()); 
            addToLevel(child, levelIndex + 1);
        });
    }
}

(我更喜欢使用Underscore / Lodash进行数据处理,并为DOM的东西保留jQuery。但只假设jQuery。)

答案 2 :(得分:0)

&amp; for fun,这是一个递归的jQuery插件,可以在一个容器上调用,该容器可能是也可能不是单身“eve”生物(取决于容器元素是否定义了name属性) :

jsfiddle

$.fn.getImps=function(imps, i)
{
    if (!$.isArray(imps)) 
        throw new Error("oook: getImps requires an empty array!");
    i=(typeof i !== "undefined" ? i : 0);

    if (this.is("[name]"))
        (imps[i] || (imps[i]=[])).push(this.attr("name")) && i++;
    this.children().each(function(){ $(this).getImps(imps,i) });
} 


btw :因为这是breadth-first traversal,&amp;通常使用非递归的基于队列的算法实现..:

jsfiddle

//expects a singleton container id 
var getImps=function(id)
{      
    var imps=[];     
    for(var o=$(id), a; (o=o.children("[name]")).length && imps.push(a=[]);)
        o.each(function() { a.push($(this).attr("name")) });
    return imps;
}

(=但只是说.. =)


Oook:你的生物似乎正在经历某种无性繁殖〜它们可能是......蚜虫?