简体   繁体   中英

javascript recursive function not working fully

I have the following recursive function but it doesnt work... It searches as far down as 'firstPageChild' and then finishes. Can anyone spot what is wrong here?.. I'm sure its something simple but its stumping me at the moment..

  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);

http://jsfiddle.net/3nkfbbyy/

Replace return findObjectById(pageVar, id); on the

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

JSFiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM