0

I can't seem to figure out why my recursive search will not behave recursively.

Do you see what's wrong? Do I have a haystack[i] in the wrong place? Because I am not seeing it. I've tried looking through examples on this site but I can't figure out something so simple.

search = function(needle, haystack) {

    len = haystack.length;
    for (var i = 0; i < len; i++)
    {
        if (typeof haystack[i] == 'object') {
            search(needle, haystack[i])
        } else {
            if (needle == haystack[i]) {
                console.log('found');
                return;
            }
            console.log('value: ' + haystack[i])
        }
    }
}

var test = [[1], [2], [3,4], [5,6]]
search(4, test)

Or see the fiddle @ http://jsfiddle.net/aniyishay/TBMmK/ (Open the Console)

1 Answer 1

3

You are missing var in front of len, it should be var len = haystack.length; otherwise it is treated as a global variable.

when haystack = [[1], [2], [3,4], [5,6]] then len = 4 but again search(4, [1]) is called then len = 1 is assinged then when the loop is returned the value of len = 1 instead of the original 4 because it is a global variable. Now i =2 and len = 1 so the loop exists

Sign up to request clarification or add additional context in comments.

4 Comments

@Doorknob yes it will... did you test it
Hm. That's interesting, why is that? (+1) Why does changing the global variable to a local one matter?
@Doorknob After the 1st recursive call, len will be set to 1 ([1].length). Returning to the original call, i < len will be false as i++ will set i to 1 as well, ending that loop and preventing further searching. Scoping len allows it to remain set to 4 for the 1st call.
Thanks so much, that makes sense. I couldn't even think of that being the problem, great find thanks so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.