递归函数导致溢出

时间:2014-02-26 21:25:23

标签: javascript recursion

我正在尝试用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);      
    }

谢谢!

1 个答案:

答案 0 :(得分:2)

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

 angular.forEach(sitemap, function ...

似乎你想要在递归上调用它

 angular.forEach(entries, function ....