簡體   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