递归Javascript函数的返回值丢失

时间:2018-03-21 17:01:19

标签: javascript function recursion

我有一个JSON字段对象

[a-z]

可以这样嵌套:

{path: 'field', children: []}

我使用以下函数在嵌套字段中迭代以检索具有指定路径的字段:

$scope.fields = [{path: 'field1', children:
                            [{path: 'field1.one', children: []},
                             {path: 'field1.two', children: []}]},
                        {path: 'field2', children: []}];

此次电话

var getField = function(thisPath, theseFields) {

        if (arguments.length == 1) {
            theseFields = $scope.fields;
        }
        angular.forEach(theseFields, function(field) {
            if (field.path == thisPath) {
                console.log('returning: '+JSON.stringify(field));
                return field;
            }
            if (field.children != null) {
                return getField(thisPath, field.children);
            }
        });
    };

在浏览器控制台中生成以下日志记录:

console.log('field1.one: '+ JSON.stringify(getField('field1.one')));

找到目标字段但从未返回!

我在方法调用

中有或没有returning: {"path":"field1.one","children":[]} field1.one: undefined 得到相同的结果
return

我错过了什么?见工作plunkr

2 个答案:

答案 0 :(得分:-2)

在此解决方案中,我在找到字段时使用异常,并立即打破循环。



const fields = [
  {
    path: 'field1', 
    children:[ 
      { 
        path: 'field1.one', 
        children: [
          { 
            path: 'field1.one.one', 
            children: [
              { 
                path: 'field1.one.one.one', 
                children: [ ]
              }
            ]
          }
        ]
      },
      {
        path: 'field1.two', 
        children: []
      }
    ]
  },
  {
    path: 'field2', 
    children:[ ]
  }
]

getField = ( fields, fieldToFind ) => {
  
  fields.map( ( field ) => {
      
     if ( field.path === fieldToFind ) {
       
       /**
       * break map 
       * avoid continue loop
       */
       throw { field: field }
       
     } else {
       
       getField( field.children, fieldToFind );
       
     }
    
  } )
  
}

try {
  
  getField( fields, 'field1.one.one.one' );
  
} catch( field ) {
  
  console.log( field );
  
}




答案 1 :(得分:-6)

    var getField = function(thisPath, theseFields) {
        var result = null;
        if (arguments.length == 1) {
            theseFields = $scope.fields;
        }
        angular.forEach(theseFields, function(field) {
            var test;
            if (field.path == thisPath) {
                console.log('returning: '+JSON.stringify(field));
                result = field;
            }
            if (field.children != null) {
                test = getField(thisPath, field.children);
                if(test!=null)
                  result = test;
            }
        });
        return result;
    }