2016-12-05 52 views
0

我用这与node.js的这是示例代码:JavaScript的递归带环

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) 
当执行命中 test(this.x)它正在退出这个 for循环

。有什么办法可以启动该功能并且不会退出for循环?

此代码出口:

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 

所需的输出将是:

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

到底什么是你'this.x'和'this.i'在做什么? – melpomene

+0

我用它来演示我遇到的问题。 – Ken

+1

你正在使用“this”完全错误。 – MSH

回答

1

这是不清楚我为什么使用递归 a for循环为基本相同的任务。你期望的结果是容易产生单独使用递归:

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

3

你只需要移动递归出的for循环:

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

test(0)