并非在每次迭代时都调用递归函数 [英] Recursive function is not called on every iteration

查看:148
本文介绍了并非在每次迭代时都调用递归函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JQuery中实现递归函数.递归函数只返回一个对象(而不是返回一系列对象)(这使我暗示它仅执行一个递归调用).

I am trying to implement a recursive function in JQuery. Instead of returning a series of objects, the recursive function only returns one object(which makes me imply that it only do one recursive call).

//recursive function to find every Base Child 
function GetBaseChild(node)
{
    if(node.hasOwnProperty("children")){
        for(var i = 0; i < node.children.length; i++){
            return GetBaseChild(node.children[i]);
        }
    }else{
        return node;
    }
}



我以为我的fall循环中的return会阻止我的循环进入下一个索引,并因此进行递归调用(因此是单个调用).知道我该怎么做.

我尝试过的事情:

最初,我从该函数解决了未定义的错误.我尝试在for循环中添加一条if语句,以测试我们是否在循环的结尾并返回该函数,但仍然无法正常工作.



I am assuming that the return in my fall loop, stops my loop from going to the next index and do a recursion call hence the single call. Any idea how I can do it.

What I have tried:

Initially I solved the undefined error from this function. I tried adding an if statement inside the for loop to test if we are at the end of the loop and return the function but still it does not work like so.

//recursive function to find every Base Child 
function GetBaseChild(node)
{
    if(node.hasOwnProperty("children")){
        for(var i = 0; i < node.children.length; i++){
            if(i < node.children.length -1){
                  GetBaseChild(node.children[i]);
               }else{
                  return GetBaseChild(node.children[i]);
               }
        }
    }else{
        return node;
    }
}



这将返回预期结果的最后一个元素.



This returns the last element of my expected result.

推荐答案

解决方案

浏览Internet并阅读一些资料后,我意识到J Query有一些局限性.我的问题是由以下事实引起的:当我使用return时,控件会跳出循环,并且根据我使用的逻辑返回第一个/最后一个结果.并且考虑到J Query将非原始类型作为引用传递的事实,我决定传递一个数组,递归函数将在以后的代码中对其进行操作和使用.这是源代码.
Solution

After browsing the Internet and reading some sources, I realized J Query has some limitations. My problem was being caused by the fact that when I use return then the control breaks out of the loop and the first/last result is returned depending on the logic I had used. And also considering the fact that J Query passes non-primitive types as references I decided to pass an array that my recursive function will manipulate and use it later in my code. Here is the source code.
//recursive function to find every Base Child
function GetBaseChild(array, node)
{
    if(node.hasOwnProperty("children")){
        for(var i = 0; i < node.children.length; i++){
            GetBaseChild(array, node.children[i]);
        }
    }else{
        array.push(node);
    }
}


这篇关于并非在每次迭代时都调用递归函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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