javascript递归函数不能完全正常工作

时间:2015-12-07 11:40:20

标签: javascript recursion

我有以下递归功能,但它不起作用...... 它的搜索范围远远超过了firstPageChild'然后完成。谁能发现这里有什么问题? 我确信它的东西很简单,但此刻它让我很难过。

  var pageMap = [{"pageID" : "mainPage",
                        "children": [{"pageID" : "firstPage",
                                   "children": [{"pageID" : "firstPageChild",
                                                 "children": []
                                                }]
                                    },
                                    {"pageID" : "secondPage",
                                   "children": [{"pageID" : "secondPageChild1",
                                                 "children": []
                                                }, {"pageID" : "secondPageChild2",
                                                 "children": []
                                                }]
                                    },
                                    {"pageID" : "thirdPage",
                                   "children": [{"pageID" : "thirdPageChild1",
                                                 "children": []
                                                }, {"pageID" : "thirdPageChild2",
                                                 "children": []
                                                }]
                                    }]
                      }];

function findObjectById(root, id) {
debugger;
var k, pageVar;
if (root.children) {
    for (k in root.children) {

        pageVar = root.children[k];

        if (pageVar.pageID == id) {
            return pageVar;
        }
        else if (pageVar.children.length) {
            return findObjectById(pageVar, id);
        }
    }
}
};

for (var i = 0, len = pageMap.length; i < len; i++) {
  var myObj = findObjectById(pageMap[i], "secondPageChild2");
}


console.log(myObj);

Dynamically access object property using variable

1 个答案:

答案 0 :(得分:1)

替换

上的return findObjectById(pageVar, id);
pageSrch = findObjectById(pageVar, id);
if(pageSrch){
   return pageSrch;
}

JSFiddle