我将其与 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)
关于JavaScript 递归与循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40982840/