1

I have a recursive function and I'm trying to create an array which will be different for each "thread" created by a for loop within the recursion.

I have an example below. In the initial pass of the function, the variable ids is undefined. I set it to be an empty array, and push the id passed into the function onto that array. In the example, this makes the ids array equal [2].

The for loop in the function recursively calls the function provided id is greater than 0. In the first pass of the for loop, recursiveFunction is called with (2-1,[2]);

This call sees that ids is not undefined, and adds 1 to the array making the array [2,1]. This 2nd pass of the function executes the for loop only once calling recursiveFunction(1-1,[2,1]).

We now enter the 3rd pass of the function, which appends zero to the array so the array is now [2,1,0]. This ends the first run of the for loop in the first run of the function.

We are now back to the second run of the for loop in the original call of the function. When we left it, the array ids was [2], however, when we log it, we can see that the recursion has affected the content of the array. This makes sense as the recursion affects the array as it's hoisted.

I am trying to find a way to avoid this, so that when recursing finishes, the first time the ids array is [2,1,0] and the second time it's also [2,1,0]. Currently, it's [2,1,0] then [2,1,0,1,0].

Is what I'm trying to do possible? Perhaps there's a workaround I should be considering. This is the code.

outerFunction = function recursiveFunction (id,ids) {

    if (typeof ids === 'undefined') {
        ids = [];
    }

    ids.push(id);

    for(var i=0;i<id;i++) {

        recursiveFunction(id-1,ids);
    }

    if (id === 0) {
        console.log('id is zero and ids is: ' + ids);
    }
 }

 outerFunction(2);

This is the fiddle: http://jsfiddle.net/hzLm4rbq/

1 Answer 1

2

You need to make a copy of the array in each invocation of your function, as all arguments reference the same array otherwise (and modify it). You can use the Array slice method for that.

function recursiveFunction (id,ids) {
    if (typeof ids === 'undefined')
        ids = [];
    else
        ids = ids.slice(); // copy

    ids.push(id);
    for (var i=0; i<id; i++)
        recursiveFunction(id-1, ids);

    if (id === 0)
        console.log('id is zero and ids is: ' + ids);
}

Now if you incorporate the i of the loop in your array, you get different outputs.

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

1 Comment

Nice work Bergi. I knew it was a referencing issue, just didn't know how to create a separate locall instance.

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.