递归函数调用返回
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
得到的值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;
}
}
}
}
相关文章:
- 从函数返回函数而不调用返回的函数
- 调用Typescript setter don't返回函数,尽管关联的getter可以工作
- node.js for循环在函数调用返回之前进行迭代,从而产生对象问题
- 让 ajax 数据返回到调用函数 - 需要澄清之前的答案
- 如何使用一些变量参数从javascript函数调用 asp.net C#函数并从C#函数获取字符串返回
- 在咖啡脚本中调用函数返回“函数未定义”
- 将数据从 executeAsync 返回给调用函数 (JavaScript/Mozilla)
- Javascript 函数返回 value.根据第一个函数返回值调用另一个函数
- 对同一 AJAX 函数的串行调用仅返回上次调用的数据
- 在 JavaScript 中,构造函数和作为构造函数调用的返回对象的函数之间有什么区别
- 为什么我的递归函数调用没有返回值
- 在 for 循环中返回函数调用的值
- 我无法让它作为 JavaScript 函数工作(我在控制台时得到我想要的返回值.log但我不能将其作为函数调用)
- 递归函数返回后的函数调用
- 当调用返回相同对象的函数时,无论是否作为构造函数调用,我都应该使用“new”吗
- 为什么在返回另一个函数调用之前对未知参数调用void
- 如何返回到调用当前函数的函数
- javascript函数调用返回未定义和页面连续加载
- 分配给变量的javascript函数调用返回未定义的结果
- 如何使用Promise将assync Angular函数的值返回到调用方法中