【问题标题】:Recursive Function Causing Overflow递归函数导致溢出
【发布时间】:2014-02-26 21:25:23
【问题描述】:

我正在尝试用 JavaScript 编写递归函数。我的功能需要搜索项目树。我创建了一个JSFiddle。当我在 Chrome 中运行 JavaScript 时,我收到一条错误消息:

RangeError: Maximum call stack size exceeded

我认为这意味着我没有在正确的时间返回我的价值。但是,我继续审查该功能,它对我来说看起来是正确的。我做错了什么?

var sitemap = [
  {
    name: 'dashboards', children: [
      { name: 'dashboard 1', route: '/dashboards/dashboard1', html: '' }
    ]
  },
  {
    name: 'objects', children: [
      { name: 'players', route: '/objects/players', html: '/objects/players.html' },
      { name: 'teams', route: '/objects/teams', html: '/objects/teams.html' },
      { name: 'coaches', route: '/objects/coaches', html: '/objects/coaches.html' },
      { name: 'cities', children: [
        { name: 'Chicago', route: '/cities/chicago',
                 html: '/objects/cities/chicago.html' },
        { name: 'Philadelphia', route: '/cities/philadelphia', html: '/objects/cities/philadelphia.html' }
]},                    
        ]
    }
];

var getFromSitemap = function (path, entries) {
    var sitemapItem = null;
    if (entries) {
        angular.forEach(sitemap, function (entry, key) {
            if (entry.hasOwnProperty("children")) {
                sitemapItem = getFromSitemap(path, entry.children);
            } else if (entry.route === path) {
                sitemapItem = entry;
            }
        });
    }
    return sitemapItem;
};

    var getItem = function() {    
var item = getFromSitemap('/cities/chicago', sitemap);
console.log(item);      
    }

谢谢!

【问题讨论】:

  • 你的功能是什么?
  • 您应该在此处发布您的代码。另外,请尝试在浏览器中使用调试器。
  • 我将您的代码添加到问题中(这是正确的 StackOverflow 过程)。

标签: javascript recursion


【解决方案1】:

您每次都在同一个对象(站点地图)上调用 foreach:

 angular.forEach(sitemap, function ...

您似乎想在条目上递归调用它

 angular.forEach(entries, function ....

【讨论】:

    猜你喜欢
    • 2011-02-26
    • 2013-04-05
    • 2020-03-06
    • 1970-01-01
    • 2018-06-19
    • 1970-01-01
    相关资源
    最近更新 更多