代码之家  ›  专栏  ›  技术社区  ›  WillMaddicott

codewars错误上的javascript迷宫运行器

  •  0
  • WillMaddicott  · 技术社区  · 7 年前

    我一直在研究密码战,我遇到了马泽鲁纳( https://www.codewars.com/kata/maze-runner/train/javascript )我被难住了大约两天!

    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
    

    任何帮助都将不胜感激!我要把我的头发拉出来!

    1 回复  |  直到 7 年前
        1
  •  1
  •   Francesco    7 年前

    您的解决方案的问题是,在移动之后,您只需检查 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';
    }