繁体   English   中英

带循环的JavaScript递归

[英]JavaScript Recursion with loop

我将其与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)

当执行命中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

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

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

test(0)

我不清楚,为什么您要对基本相同的任务使用递归 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); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM