javascript - 我真的必须为这个递归函数使用全局变量吗?

标签 javascript recursion

我有一个递归函数,恰好是一个 for 循环

function deepFindGroup(groupName, currentGroup) {
    console.log("Testing");
    for (e in currentGroup) {

        if (currentGroup[e].intName == groupName) {
            console.log(currentGroup[e]["Members"]);
            return currentGroup[e]["Members"];
        } else if (currentGroup[e]["Members"]) {
            return deepFindGroup(groupName, currentGroup[e]["Members"]);
        }
    }
}

看来我无法用有意义的 return 语句来处理所有可能性。例如,如果 currentGroup[e].intName 不等于 groupName,并且该分支的子级没有成员属性(在本例中它根本没有子级)。它最终返回未定义。我能想到的唯一解决方案是创建一个全局变量,我试图避免这种情况。

编辑: 该函数应该返回树中的给定分支。该树由包含“成员”的对象(具有 intName 属性)组成,“成员”本身可以是包含其他成员的对象。成员也可以不包含任何内容,但仍然有一个 intName。

看起来像这样:

Gengroup_1--intName: Gengroup_1
          |
          --Members-- nochild -- intName: nochild
                    |
                    --Gengroup_2--intName: Gengroup2
                                 |
                                 --Members-- object -- intName: object
                                           |
                                           -- anotherObject -- intName: anotherObject

最佳答案

定义进入函数时的结果,当发现某些东西时停止迭代:

function deepFindGroup(groupName, currentGroup) {
  var result = null;

  for (e in currentGroup) {
    if (currentGroup[e].intName === groupName) {
      result = currentGroup[e]["Members"];
    } else if (currentGroup[e]["Members"]) {
      result = deepFindGroup(groupName, currentGroup[e]["Members"]);
    }
    
    if (result || result === undefined) break;
  }
  
  return result;
}

var group = {
  one: {
    intName: 'one',
    Members: {
      one_one: {
        intName: 'one_one',
      }
    }
  },
  two: {
    intName: 'two',
    Members: {
      two_one: {
        intName: 'two_one',
        Members: {}
      }
    }
  }
}

console.log(deepFindGroup('one', group)) // -> {one_one: {intName: 'one_one'}}
console.log(deepFindGroup('one_one', group)) // -> undefined (members are undefined)
console.log(deepFindGroup('two_one', group)) // -> {}
console.log(deepFindGroup('two_two', group)) // -> null

请记住,当匹配组的 currentGroup[e]["Members"]undefined 时,您将得到 undefined 为结果,因此,如果结果是未定义数组任何意味着在成员中,则该组被匹配,如果null 未找到。

关于javascript - 我真的必须为这个递归函数使用全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45900793/

相关文章:

php - 用于视频播放的 Javascript 监听器 - 发送到数据库

c - 为什么它显示主要因子的输出错误?

java - Java中的递归任务

recursion - F# - 在运行时创建递归可区分联合

javascript - AngularJS-ng :model - Field is readonly when bound to $q promise?

javascript - 如何修复非数字值?

c - 如何使用递归在链表中添加整数?

php - 通过相关实体正确递归

javascript - 如何从 stackoverflow 等网站运行 javascript 示例?

javascript - 如何在jquery中延迟加载外部页面