0

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
4
  • 5
    What the heck are you doing with this.x and this.i? Commented Dec 5, 2016 at 20:38
  • I'm using it to demonstrate the issue I'm having. Commented Dec 5, 2016 at 20:40
  • 2
    You are using "this" totally wrong. Commented Dec 5, 2016 at 20:47
  • 2 issues here: global context (this) and wrong place for recursive call(should be outside of loop) Commented Dec 5, 2016 at 21:03

2 Answers 2

3

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)
Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

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.