简体   繁体   English

JavaScript中的递归函数问题

[英]Issue with recursive function in javascript

I am practicing using recursive functions to solve some simple javascript problems. 我正在练习使用递归函数来解决一些简单的JavaScript问题。

I am running into an issue with the following code, 我遇到了以下代码的问题,

var locate = function(arr,value){
    for (var i=0; i <arr.length; i++) {
        if(typeof arr[i]=== "string") {
            console.log("string is string");
            if(arr[i]=== value) {
                console.log("This should be true");
                return true;
            }
        }
        else {
            locate(arr[i], value);
        } 
    }
}
console.log(locate(['d', 'a',['e', 'g']], 'e'));

I cannot get this program to return true. 我无法使该程序返回true。 It gets to the right part of the code, as it prints the statement above it. 它到达代码的正确部分,因为它在其上面打印了语句。

Any help would be appreciated. 任何帮助,将不胜感激。 I have been banging my head at this for a couple of hours now. 我已经为此努力了几个小时。

Edit-@Matt Burland pointed out the fact that you need to include a return statement when calling the recursive. Edit- @ Matt Burland指出了以下事实:调用递归时需要包括return语句。

When you recurse, you need to return the value returned by the recursive call as you unwind. 递归时,您需要在展开时返回递归调用返回的值。

So in your else clause, you need: 因此,在您的else子句中,您需要:

return locate(arr[i], value);

 var locate = function(arr,value){ for (var i=0; i <arr.length; i++) { if(typeof arr[i]=== "string") { console.log("string is string"); if(arr[i]=== value) { console.log("This should be true"); return true; } } else { return locate(arr[i], value); } } } alert(locate(['d', 'a',['e', 'g']], 'e')); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM