gpt4 book ai didi

Javascript Maze Runner 出现 Codewars 错误

转载 作者:行者123 更新时间:2023-12-01 01:59:13 27 4
gpt4 key购买 nike

我一直在研究代码 war ,并且遇到了 mazerunner (https://www.codewars.com/kata/maze-runner/train/javascript),我已经被难住了大约 2 天!

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] 将在某个时刻未定义(向南移动一段时间)。我猜想在同一点 y 将是 3,因此错误 Cannot read property '3' of undefined

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

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

关于Javascript Maze Runner 出现 Codewars 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50749351/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com