JavaScript + recursive function returning undefined

穿精又带淫゛_ 提交于 2021-02-15 03:12:53

问题


I have a simple html structure that I need to traverse. For some reason my recursive function returns 'undefined' on any nested nodes, but not for parent nodes. Unfortunately this needs to be native js, no jQuery for this one. Thanks!

HTML:

<div id="container">
  <div id="head"> 
    <span id="left"><</span> 
    <span id="right">></span> 
  </div>
</div>

Script:

var h = hasId(container, 'head');
var l = hasId(container, 'left');
var r = hasId(container, 'right');

console.log(h + " : " + r + " : " + l);
//[object HTMLDivElement] : undefined : undefined

function hasId(ele, id) {
    for (var i = 0; i < ele.childNodes.length; i++) {
        var child = ele.childNodes[i];
        if(child.id == id) return child;
        else hasId(child, id);
    }
}

回答1:


You are simply the call to return on the recursive call. Also, you should test whether its result is defined. If yes, you can return it, or continue looping if not.

var h = hasId(container, 'head');
var l = hasId(container, 'left');
var r = hasId(container, 'right');

console.log(h + " : " + r + " : " + l);
//[object HTMLDivElement] : undefined : undefined

function hasId(ele, id) {
    for (var i = 0; i < ele.childNodes.length; i++) {
        var child = ele.childNodes[i];
        if(child.id == id) return child;
        else {
          var next = hasId(child, id);
          if(next) return next;
        };
    }
}​



回答2:


The else clause should return the value of hasId(child, id), but only if that value is itself defined, otherwise it has to continue through the loop.

Without a return the function will recurse, but not give an answer.




回答3:


You can fix it like this :

var h = hasId(container, 'head');
var l = hasId(container, 'left');
var r = hasId(container, 'right');

console.log(h + " : " + r + " : " + l);

function hasId(ele, id) {
    for (var i = 0; i < ele.childNodes.length; i++) {
        var child = ele.childNodes[i];
        if(child.id == id || (child = hasId(child, id))){
           return child;
        }
    }
    return false;
}


来源:https://stackoverflow.com/questions/10762312/javascript-recursive-function-returning-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!