代码战争错误上的Javascript迷宫运行程序
我一直在努力完成代码战,我遇到了mazerunner(),我被难倒了大约两天代码战争错误上的Javascript迷宫运行程序,javascript,maps,codewarrior,Javascript,Maps,Codewarrior,我一直在努力完成代码战,我遇到了mazerunner(),我被难倒了大约两天 function mazeRunner(maze, directions) { //find start value var x = 0; //x position of the start point var y = 0; //y position of the start point for (var j = 0 ; j < maze.length ; j++){ if (maze[j].index
function mazeRunner(maze, directions) {
//find start value
var x = 0; //x position of the start point
var y = 0; //y position of the start point
for (var j = 0 ; j < maze.length ; j++){
if (maze[j].indexOf(2) != -1){
x = j;
y = maze[j].indexOf(2)
}
} // end of starting position forloop
console.log(x + ', ' + y)
for (var turn = 0 ; turn < directions.length ; turn++){
if (directions[turn] == "N"){
x -= 1;
}
if (directions[turn] == "S"){
x += 1;
}
if (directions[turn] == "E"){
y += 1;
}
if (directions[turn] == "W"){
y -= 1;
}
if (maze[x][y] === 1){
return 'Dead';
}else if (maze[x][y] === 3){
return 'Finish';
}
if (maze[x] === undefined || maze[y] === undefined){
return 'Dead';
}
}
return 'Lost';
}
任何帮助都将不胜感激!这件事让我毛骨悚然 您的解决方案的问题是,在移动之后,您只需检查
maze[x][y]
在失败的测试中,maze[x]
将在某个点未定义
(向南移动一段时间)。我猜在同一点上y
将是3
,因此错误无法读取未定义的属性“3”
为了避免这种情况,在尝试访问坐标之前,应将测试未定义的代码上移:
// move this as first check
if (maze[x] === undefined || maze[y] === undefined){
return 'Dead';
}
您的解决方案的问题是,在移动之后,您只需检查
maze[x][y]
在失败的测试中,maze[x]
将在某个点未定义
(向南移动一段时间)。我猜在同一点上y
将是3
,因此错误无法读取未定义的属性“3”
为了避免这种情况,在尝试访问坐标之前,应将测试未定义的代码上移:
// move this as first check
if (maze[x] === undefined || maze[y] === undefined){
return 'Dead';
}
哇!那真是太棒了!谢谢这是有道理的,而且行之有效!!我已经搔头好几天了!再次感谢!哇!那真是太棒了!谢谢这是有道理的,而且行之有效!!我已经搔头好几天了!再次感谢!