Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/426.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
代码战争错误上的Javascript迷宫运行程序_Javascript_Maps_Codewarrior - Fatal编程技术网

代码战争错误上的Javascript迷宫运行程序

代码战争错误上的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

我一直在努力完成代码战,我遇到了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].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';
}

哇!那真是太棒了!谢谢这是有道理的,而且行之有效!!我已经搔头好几天了!再次感谢!哇!那真是太棒了!谢谢这是有道理的,而且行之有效!!我已经搔头好几天了!再次感谢!