递归函数调用返回

Recursive function call returns

本文关键字:返回 函数调用 递归      更新时间:2023-09-26

我正在递归地迭代一个潜在的无限嵌套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得到的值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;
              }
          }
      }
  }