【发布时间】:2019-09-13 06:33:24
【问题描述】:
好吧,Stackoverflow 第一次在这里发帖。我很茫然,如果有任何帮助,我将不胜感激。
我有一个递归函数,它似乎可以正常工作,直到我尝试从它返回。 (只是一个有趣的小迷宫赛跑者)
当到达 return 语句时,它似乎循环回到 if(grid[y+1][x] ===2) 语句。
然后我看不到该函数再次被调用,但y 和x 的值开始变化,因为它在函数周围循环,然后到达底部的else 并返回那里。
我还在控制台中看到“内部 return if”,在浏览器中设置断点显示 return 语句被调用,只是不退出函数。
提前非常感谢!!!
const grid =[0,0,0,0,3,2],
[0,0,0,0,3,0],
[0,0,0,0,3,0],
[3,3,3,3,3,0],
[0,0,0,0,0,0],
[1,3,3,3,3,3]
],
const recursiveSearch = (y, x) => { // init values y=5 x=0
console.log(y + ' ' + x);
if(grid[y-1]){
if(grid[y-1][x] === 0) {
grid[y-1][x] = 4;
recursiveSearch(y-1, x);
}
if(grid[y-1][x] === 2) {
console.log('inside return if');
return 'end point found at';
}
}
if(grid[y][x+1] || grid[y][x+1] === 0) {
if(grid[y][x+1] === 0) {
grid[y][x+1] = 4;
recursiveSearch(y,x+1);
}
if(grid[y][x+1] === 2) {
return "end point found at";
}
}
if(grid[y+1] || grid[y+1] === 0) {
if(grid[y+1][x] === 0) {
grid[y+1][x] = 4;
recursiveSearch(y+1,x);
}
if(grid[y+1][x] === 2) {
return "end point found at";
}
}
if(grid[y][x-1] || grid[y][x-1] === 0 ) {
if(grid[y][x-1] === 0) {
grid[y][x-1] = 4;
recursiveSearch(y,x-1);
};
if(grid[y][x-1] === 2) {
return "end point found at";
}
} else {
return "No solution found"
}
};
【问题讨论】:
-
递归调用
recursiveSearch时没有返回任何内容
标签: javascript recursion return