递归Javascript函数的返回值丢失

递归Javascript函数的返回值丢失,javascript,function,recursion,Javascript,Function,Recursion,我有一个JSON字段对象 {path: 'field', children: []} 可以像这样嵌套: $scope.fields = [{path: 'field1', children: [{path: 'field1.one', children: []}, {path: 'field1.two', children: []}]},

我有一个JSON字段对象

{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 getField(thisPath, field.children)

我错过了什么?请参阅工作。

在这个解决方案中,我在找到字段时使用异常,这会立即中断循环

常量字段=[ { 路径:'field1', 儿童:[ { 路径:“field1.one”, 儿童:[ { 路径:“字段1.1.1”, 儿童:[ { 路径:“field1.1.1.1.1”, 儿童:[] } ] } ] }, { 路径:“field1.two”, 儿童:[] } ] }, { 路径:'field2', 儿童:[] } ] getField=字段,fieldToFind=>{ fields.map字段=>{ 如果field.path==fieldToFind{ /** *分解图 *避免继续循环 */ 抛出{field:field} }否则{ getField.children,fieldToFind; } } } 试一试{ getField字段,“field1.1.1.1”; }渔场{ console.log字段;
}考虑返回语句从提示返回的函数:它不是getField。在这种情况下,一个好的老式for循环将非常有用。超级感谢您的快速回答!如果你认为它是正确的,请将它标记为正确答案,这样我就可以获得学分。我如何将它标记为正确答案?
    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;
    }