为什么Codewars上的Javascript Maze 运行错误?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (40)

以下代码出现了一些问题:

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';

}

运行这个程序时,大多数情况下都能工作正常,但是在最后一个场景中,出现报错:

TypeError: Cannot read property '3' of undefined
at mazeRunner
at /home/codewarrior/index.js:87:19
at /home/codewarrior/index.js:155:5
at Object.handleError

有谁能帮我解决吗?

提问于
用户回答回答于

在移动之后,只需检查maze[x][y],maze[x]在某一时刻undefined(向南移动一段时间),我想在这一点上y会是3,因此会报错Cannot read property '3' of undefined

为了避免这种情况,在尝试访问坐标之前,应该将测试未定义的代码移到上面:

// move this as first check
if (maze[x] === undefined || maze[y] === undefined){
  return 'Dead';
}

扫码关注云+社区

领取腾讯云代金券