Javascript和深度跟踪中的递归函数 [英] Recursive functions in Javascript and depth-tracking

查看:73
本文介绍了Javascript和深度跟踪中的递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在JS编写递归函数并遇到一些麻烦。让我们从这个非常基本的函数开始:

I'm writing a recursive function in JS and having some trouble. Let's start with this very basic function:

function traverse(thing)
{
    if (typeof traverse.depth == 'undefined')
        traverse.depth = 1;
    else
        traverse.depth ++;

    if (thing.child)
        traverse(thing.child);
}

所以这个工作正常,深度充当静态var的排序,但问题是在像C这样具有适当静态变量的语言中,当你退出函数时,这个变量会(表面上)减少,所以它是真正的深度。如果我有三个盒子,其中包含三个盒子,每个盒子包含三个盒子等,我们基本上钻到最深的盒子里,直到没有孩子,然后退出一个级别给一个兄弟姐妹,并穿过它的孩子。上述代码的问题在于深度不断增加和增加,即使从最老的祖先到最小的孩子,TRUTH深度可能只有3或4。如果每个级别上有80个兄弟姐妹,那个深度计数器将会飙升。

So this works fine, and depth acts as a static var of sorts, but the problem is that in a language like C that has proper static vars, as you back out of the function, this variable would (ostensibly) decrease, so it is a true depth. If I have three boxes that contain three boxes and each of those contain three boxes, etc., we're essentially drilling down into the deepest one till there are no children, then backing out up a level to a sibling, and traversing its children. The problem with the above code is that the depth keeps increasing and increasing infinitely, even though the TRUTH depth may only be 3 or 4 from the oldest ancestor to the youngest child. If there are 80 siblings on each level, that depth counter is going to skyrocket.

如何跟踪JS递归函数的真实深度?

How do I keep track of true depth in JS recursive functions?

推荐答案

请勿将计数器附加到该功能。计数器由所有递归调用共享,因此计数器表示函数调用的数量,而不是递归深度。

Don't attach the counter to the function. The counter is shared by all recursive calls, so the counter represents the number of function calls, instead of the recursion depth.

深度作为单独的变量传递,计数器显示真实的深度。

When depth is passed as a separate variable, the counter shows the true depth.

function traverse(thing, depth)
{
    if (typeof depth == 'number')
        depth++;
    else
        depth = 1;

    if (thing.child)
        traverse(thing, depth);
}

这篇关于Javascript和深度跟踪中的递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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