2016-12-05 55 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)