这是源数据。我想在源代码中使用"hello“,找到"up",最后得到一个数组"max,min”(像多个树一样,找到根)
var obj = {
'hello': {
"up": "world",
"down": "ccc"
},
'world': {
"up": ["max","min"],
"down": "hello"
},
'max': {
"up": null,
"down": "world"
},
'min': {
"up": null,
"down": "world"
},
'ccc': {
"up": "hello",
"down": null
}
}
我使用了一个递归函数,但是下面的代码不起作用。它返回"undefined“。(如果"up“不是数组,则该函数有效。)
function findRoot(source,key){
var up = source[key]['up'];
if(up==null){
return key
}else{
if(Object.prototype.toString.call(up)=='[object Array]'){
up.forEach(function(d){
return findRoot(source,d);
})
}else{
return findRoot(source,up)
}
}
}
我如何修复这段代码?
发布于 2015-08-03 21:15:42
在'if array‘的情况下没有返回任何东西:
if(Object.prototype.toString.call(up)=='[object Array]'){
up.forEach(function(d){
return findRoot(source,d);
})
// no return
如果不指定返回,JavaScript将默认返回undefined
。
还要注意,forEach
函数不会对函数返回的值执行任何操作。一种替代方法是使用map
函数,然后再次返回该数组:
var results = up.map(function(d) {
return findRoot(source, d);
});
return array;
然而,这也可能不是你想要做的事情。由于您的代码的唯一基本情况是当值为null时,您的函数将只返回null或包含null的数组,而不是返回有意义的内容。例如,调用findRoot(obj, 'hello');
将返回[null, null]
,这可能不是您想要的结果。
如果是这样的话,你可能想要重新思考你的递归函数到底是做什么的,并考虑添加更多的基本用例,或者修改现有的基本用例和递归用例。
发布于 2015-08-03 21:21:14
问题是您在forEach()
循环中的匿名函数内部返回,实际上并没有为findRoot()
返回任何内容,所以默认情况下它返回undefined
。
up.forEach(function(d){
return findRoot(source,d);//doesn't return for **findRoot()** just for anonymous function.
});
如果有多个根节点,您可以做的是返回一个根节点数组。您可以将返回值推送到array
,然后返回数组。如果不超过一个,你可以像平常一样返回。下面是一个示例:
function findRoot(source,key){
var up = source[key]['up'];
if(up==null){
return key
}else{
if(Object.prototype.toString.call(up)=='[object Array]'){
var temp = new Array();
up.forEach(function(d){
temp.push(findRoot(source,d));
});
return temp;
}else{
return findRoot(source,up)
}
}
}
如果你有一个数组,它会像这样返回:
如果你没有数组,它会像这样返回:
然后,您可以检查返回值是否为数组,并根据需要对返回值执行操作。另一种选择是总是返回一个数组,如果只有一个元素,那么数组中就只有一个元素。
https://stackoverflow.com/questions/31788164
复制相似问题