Javascript无限递归函数

时间:2017-11-06 17:31:44

标签: javascript recursion google-apps-script

我有以下tags个对象数组:

[
  {
    "tagName": "Optimizely Setup",
    "children": [],
  },
  {
    "tagName": "Adobe DTM Bootstrap",
    "children": [
      {
        "tagName": "Adobe Analytics",
        "children": [
          {
            "tagName": "Adobe Analytics",
            "children": []
          }
        ]
      }
    ]
  },
  {
    "tagName": "Google Content Experiments",
    "children": []
  },
  {
    "tagName": "Google Tag Manager",
    "children": []
  },
  {
    "tagName": null,
    "children": [
      {
        "tagName": "Wordpress Stats",
        "children": [],

      }
    ]
  },
  {
    "tagName": "AddThis Widget",
    "children": [
      {
        "tagName": "AddThis",
        "children": [],
      }
    ]
  }
]

我的目标是检查每个对象的tagName。如您所见,任何对象都可以拥有需要children检查的嵌套tagName对象数组。

我正在尝试使用递归函数,但我陷入无限循环......

  var tagNameArr = [];
  var findObjectByLabel = function(obj) {
    for(i = 0; i < obj.length; i++) {
      if(obj[i].tagName != null){
        var tms = obj[i].tagName.match(/Adobe DTM Bootstrap|Google Tag Manager/g)
        if(tms === null) {
          tagNameArr.push(obj[i].tagName)
          if(obj[i].children.length > 0) {
            findObjectByLabel(obj[i].children)
          }

        }

      }

    }
    return null;
  }
  findObjectByLabel(tags);

这是我第一次使用递归,任何解决方案都会有很多帮助

发现错误:for循环缺少变量初始化

0 个答案:

没有答案