Ken
Ken

Reputation: 215

JavaScript Recursion with loop

I'm using this with Node.JS This is the example code:

function test(x){
    this.x = x
    for (this.i = 0; this.i < 10; this.i++) {
        console.log(this.x + ' - ' + this.i)
        if (this.x < 3) {
            this.x++
            test(this.x)
        }
    }

}

test(0)

when execution hits test(this.x) it is exiting the for loop. Is there any way to kick off the function and not exit the for loop?

This code exports:

0 - 0
1 - 0
2 - 0
3 - 0
3 - 1
3 - 2
3 - 3
3 - 4
3 - 5
3 - 6
3 - 7
3 - 8
3 - 9

The desired output would be:

0 - 0
0 - 1
0 - 2
0 - 3
0 - 4
0 - 5
0 - 6
0 - 7
0 - 8
0 - 9
1 - 0
1 - 1
1 - 2
1 - 3
1 - 4
1 - 5
1 - 6
1 - 7
1 - 8
1 - 9
2 - 0
2 - 1
2 - 2
2 - 3
2 - 4
2 - 5
2 - 6
2 - 7
2 - 8
2 - 9
3 - 0
3 - 1
3 - 2
3 - 3
3 - 4
3 - 5
3 - 6
3 - 7
3 - 8
3 - 9

Upvotes: 0

Views: 2771

Answers (2)

Jordan Running
Jordan Running

Reputation: 106027

It's not clear to me why you're using recursion and a for loop for basically the same task. Your desired result is easy to produce using recursion alone:

function test(x, y) {
  if (x > 3) {
    return;
  }
  
  if (y === undefined) {
    y = 0;
  } else if (y > 9) {
    return test(x + 1);
  }
  
  console.log('%d - %d', x, y);
  test(x, y + 1);
}

test(0);

Upvotes: 2

idbehold
idbehold

Reputation: 17168

You just need to move the recursion out of the for-loop:

function test(x){
    for (var i = 0; i < 10; i++) {
        console.log(x + ' - ' + i)
    }
    if (x < 3) {
        test(x + 1)
    }
}

test(0)

Upvotes: 3

Related Questions