目前,我在现有的角度控制器中使用递归函数来生成基于树结构的索引数组,该树结构正在创建指定目标值的“分支”。该函数的目的是以递归方式检查深层嵌套对象的值,并循环显示它们可能出现的数组。该函数一直有效,直到找到目标节点并匹配它。在返回调用上,基于我所知道的,应该循环回到for循环。相反,它退出函数并返回undefined
。我注意到抛出的错误是由Angular生成的,如下所示。
angular.js:13236 ReferenceError: result is not defined
at questionsController.self.findIndex (questions-controller.js:724)
at questionsController.self.findIndex (questions-controller.js:734)
at questionsController.self.findIndex (questions-controller.js:724)
at questionsController.self.addQuestions (questions-controller.js:711)
at fn (eval at compile (angular.js:14086), <anonymous>:4:262)
at expensiveCheckFn (angular.js:15076)
at callback (angular.js:24546)
at Scope.$eval (angular.js:16820)
at Scope.$apply (angular.js:16920)
at HTMLButtonElement.<anonymous> (angular.js:24551)
功能如下:
self.findIndex = function (map, target, arr, index) {
if (map instanceof Array) {
for (var x = 0; x < map.length; x++) {
var newArr = arr.slice();
newArr.push(x);
result = self.findIndex(map[x], target, newArr, x);
if (result.length > 0) {
return result;
}
}
} else if (map instanceof Object) {
if (map.id == target.id) {
return arr;
}
else if (map.questions && map.questions.length > 0) {
return result = self.findIndex(map.questions, target, arr, index);
}
}
return [];
};
数据模型如下:
[
{
id: 1,
name: 'foo',
questions: [
{
id: 2,
name: 'bar',
questions: []
}
]
},
{
id: 3,
name: 'foobar',
questions: [
{
id: 4,
name: 'barfoo',
questions: [
{
id: 5,
name: 'foobarfoo',
questions: []
},
{
id: 6,
name: 'barfoobar',
questions: []
}
]
}
]
}
]
如果有关此问题的任何其他信息可能有助于提供清晰度,请与我们联系。