Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/430.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ajax/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带循环的JavaScript递归_Javascript_Recursion - Fatal编程技术网

带循环的JavaScript递归

带循环的JavaScript递归,javascript,recursion,Javascript,Recursion,我在Node.JS中使用这个示例代码: 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)

我在Node.JS中使用这个示例代码:

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)
所需的输出将是:

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

您只需要将递归移出for循环:

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

test(0)
功能测试(x){
对于(变量i=0;i<10;i++){
console.log(x+'-'+i)
}
if(x<3){
测试(x+1)
}
}
测试(0)

您只需将递归移出for循环:

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

test(0)
功能测试(x){
对于(变量i=0;i<10;i++){
console.log(x+'-'+i)
}
if(x<3){
测试(x+1)
}
}
测试(0)

我不清楚为什么要对基本相同的任务使用递归和
for
循环。仅使用递归即可轻松生成所需的结果:

功能测试(x,y){
如果(x>3){
返回;
}
如果(y==未定义){
y=0;
}如果(y>9),则为else{
返回试验(x+1);
}
控制台日志(“%d-%d',x,y);
试验(x,y+1);
}

试验(0)我不清楚为什么要对基本相同的任务使用递归和
for
循环。仅使用递归即可轻松生成所需的结果:

功能测试(x,y){
如果(x>3){
返回;
}
如果(y==未定义){
y=0;
}如果(y>9),则为else{
返回试验(x+1);
}
控制台日志(“%d-%d',x,y);
试验(x,y+1);
}

试验(0)
你到底在用
this.x
this.i
做什么?我用它来证明我的问题。你用“this”完全错了。这里有两个问题:全局上下文(this)和递归调用的错误位置(应该在循环之外)你到底在用
this.x
this.i
做什么?我用它来证明我的问题。你用“this”完全错了。这里有两个问题:全局上下文(this)和递归调用的错误位置(应该在循环之外)