简体   繁体   English

递归函数调用返回

[英]Recursive function call returns

I'm iterating over a potentially infinitely-nested JSON recursively. 我递归地遍历了一个可能无限嵌套的 JSON。

This is the function I use to do this: 这是我用来执行此操作的功能:

  function iterate(obj,matchId) {
      for(var key in obj) {
          var elem = obj[key];

          if(obj.id == matchId) { //if objects id matches the arg I return it
            console.log(obj); // matched obj is always logged
            return(obj);
          }

          if(typeof elem === "object") { // is an object (plain object or array),
                                         // so contains children
              iterate(elem,matchId); // call recursively
          }
      }
  }

And this is how I call it: 这就是我所说的:

var matchedObj = iterate(json,3);

However, matchedObj get's value undefined since the return value usually comes from calling iterate() from within itself and not directly by var matchedObj = iterate(json,3); 但是, matchedObj get的值undefined因为返回值通常来自于自身内部的调用iterate() ,而不是直接由var matchedObj = iterate(json,3);


Only way I can see now is to use a callback from within the recursive function to perform whatever action I want to do. 我现在看到的唯一方法是在递归函数中使用回调来执行我想执行的任何操作。 Is there any other way I'm missing? 还有其他我想念的方式吗?


In any case, this is my JSON: 无论如何,这是我的JSON:

var json =  [

    {
        "id": 1,
        "text": "Boeing",
        "children": [
            {
                "id": 2,
                "text": "747-300",
                "json": "737 JSON"
            },
            {
                "id": 3,
                "text": "737-400",
                "json": "737 JSON"
            }
        ]
    },
    {
        "id": 4,
        "text": "Airbus",
        "children": [
            {
                "id": 5,
                "text": "A320",
                "json": "A320 JSON"
            },
            {
                "id": 6,
                "text": "A380",
                "json": "A380 JSON"
            }
        ]
    }

]

You just need to return the recursive call if it found the result. 如果找到结果,您只需要返回递归调用。

function iterate(obj,matchId) {
      for(var key in obj) {
          var elem = obj[key];

          if(obj.id == matchId) { //if objects id matches the arg I return it
            console.log(obj); // matched obj is always logged
            return(obj);
          }

          if(typeof elem === "object") { // is an object (plain object or array),
                                         // so contains children
              var res = iterate(elem,matchId); // call recursively
              if (res !== undefined) {
                return res;
              }
          }
      }
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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