递归函数返回未定义的值

时间:2019-09-06 06:23:05

标签: javascript

我想从多级结构中获取对象

我为它编写了函数,但是即使返回它时,它也不会从函数中返回并返回值,但它会继续进行下一个递归。我知道它的返回值返回到先前调用的函数,并且由于其作用域被阻塞而被覆盖,所以这就是返回未定义值的原因

  var selectedObj = findObjectByUid( existingStructure, selectedUid);
function findObjectByUid( root, selectedUid ) {
    if( root.uniqueId === selectedUid ) {
        return root;
    }
    if( root.children && root.children.length > 0 ) {
        for( var k in root.children ) {
            if( root.children[ k ].uniqueId === selectedUid ) {
                return root.children[ k ];
            } else if( root.children.length ) {
                return findObjectByUid( root.children[ k ], selectedUid );
            }
        }
    }
}

在这里,我想在匹配到uid时返回到我的初始调用函数。

3 个答案:

答案 0 :(得分:1)

实际上,无论找到哪个节点,您都会带着第一个孩子回来。

您可以使用一个临时变量并存储子级检查的结果,如果不错误,则返回此值。

顺便说一句,您可以直接将数组的子级作为递归。

function findObjectByUid(root, selectedUid) {
    if (root.uniqueId === selectedUid) return root;
    if (!root.children || !root.children.length) return;
    for (let child of root.children) {
        let temp = findObjectByUid(child, selectedUid);
        if (temp) return temp;
    }
}

var selectedObj = findObjectByUid(existingStructure, selectedUid);

答案 1 :(得分:0)

在阵列上使用此方法存在三个问题。首先,for ... in还可以迭代对象的原型属性(如果这些属性是可枚举的)。例如:

Array.prototype.voice = "James Earl Jones";

var tMinus = [
  "Two",
  "One",
  "Blast off!"
];

var countdown = "";

for (var step in tMinus) {
  countdown += tMinus[step] + "\n";
}

console.log(countdown);
// => "Two
//    One
//    Blast Off!
//    James Earl Jones
//    "

可以通过使用hasOwnProperty排除原型属性来解决。 示例:

for (var step in tMinus) {
  if (tMinus.hasOwnProperty(step)) {
    countdown += tMinus[step] + "\n";
  }
}

答案 2 :(得分:0)

此处为正确的代码。您已在内部调用中使用return findObjectByUid,在完成循环之前,该调用将终止代码。

function findObjectByUid( root, selectedUid ,foundArr) {

  if( root.uniqueId === selectedUid ) {
    foundArr.push(root);
      return root;
  }
  else if( root.children && root.children.length > 0 ) {
      for( var k in root.children ) {
           findObjectByUid( root.children[k], selectedUid,foundArr ); 
          if(root.children[k]=== selectedUid){break;}
      }
  }
   return foundArr.length>0?foundArr[0]:null;
}

示例json和调用方法

var root = {uniqueId:1,children:[{uniqueId:10},{uniqueId:11,children:[{uniqueId:21,children:[]},{uniqueId:22,children:[]},{uniqueId:23,children:[{uniqueId:31,children:[]},{uniqueId:32,children:[]}]}]},{uniqueId:12,children:[]},{uniqueId:13,children:[]}]};
findObjectByUid(root,32,[]);
相关问题