繁体   English   中英

递归函数调用返回

[英]Recursive function call returns

我递归地遍历了一个可能无限嵌套的 JSON。

这是我用来执行此操作的功能:

  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
          }
      }
  }

这就是我所说的:

var matchedObj = iterate(json,3);

但是, matchedObj get的值undefined因为返回值通常来自于自身内部的调用iterate() ,而不是直接由var matchedObj = iterate(json,3);


我现在看到的唯一方法是在递归函数中使用回调来执行我想执行的任何操作。 还有其他我想念的方式吗?


无论如何,这是我的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"
            }
        ]
    }

]

如果找到结果,您只需要返回递归调用。

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