I have a recursive JSON crawler function that looks for a specified function then returns it. However, it is returning undefined and I am not sure why.
Here is the script:
function get(what, where){
where = typeof(where) != 'undefined' ? where : user.object;
for(entry in where){
if(typeof(where[entry]) =="string开发者_运维知识库"){
if (entry == what) {
result = where[entry];
console.log(result)
return result;
}
}else if(typeof(where[entry]) =="object"){
get(what, where[entry]);
}
}
}
the console.log
returns correctly but the return statement below it fails.
It's because you're not returning your recursive branch of the code, this:
get(what, where[entry]);
should be:
return get(what, where[entry]);
So on that branch, though you're executing all the way down, you're not returning the result back up, so you get the default return: undefined
.
If you dont write a return-statement in a JavaScript function, but it reaches its end anyway, then it returns undefined. That is (probably) what has happened here, since if you dont enter the if-statement with the return-statement, you will not get to return anything.
EDIT:
As a rule of thumb, you should ALWAYS return something in every bransch of your code. A static language compiler would have warned you about this, but here you have to make sure yourself.
Example:
function get(what, where){
where = typeof(where) != 'undefined' ? where : user.object;
for(entry in where){
if(typeof(where[entry]) =="string"){
if (entry == what) {
result = where[entry];
console.log(result)
return result;
}
}else if(typeof(where[entry]) =="object"){
get(what, where[entry]);
// Are you sure you don't want to return anything here?.. hm...
}
}
// Here be dragons! What will be returned from the function?
// Hint: Undefined! :)
}
Both those places could probably use return statements. The last one need one because what if the for-loop doesn't have any entries to enumerate over?
You probably want to modify the code:
get(what, where[entry]);
to
return get(what, where[entry]);
:-P
精彩评论