返回函数在我的代码中不起作用,导致无限循环



我正在解决JavaScript中的递归问题。但是,当第一个if语句为true时,return语句不会退出脚本,从而导致无限循环。

function steps(n, row = 0, col = 0, stair = '') {
if (row === n) {
return;
} 
if (col >= n ) {
console.log(stair);
steps(n, row + 1);
} 
if (col <= row) {
stair += '#';
} else {
stair += ' ';
}

steps(n, row, col +1, stair)
}

不,问题是在第一次递归调用之后没有返回,所以它总是会执行第二次,并且没有增加row,所以这是一个无限循环。

这项工作:

function steps(n, row = 0, col = 0, stair = '') {
if (row === n) {
return;
} 
if (col >= n ) {
console.log(stair);
steps(n, row + 1);
} else {
if (col <= row) {
stair += '#';
} else {
stair += ' ';
}

steps(n, row, col +1, stair)
}
}
// try it:
steps(5);

感谢Christian指出我缺少退货。这是我现在的工作代码:

function steps(n, row = 0, col = 0, stair = '') {
if (row === n) {
return 0;
} 
if (col >= n ) {
console.log(stair);
steps(n, row + 1);
return;
} 

if (col <= row) {
stair += '#';
} else {
stair += ' ';
}

steps(n, row, col +1, stair)
}

最新更新