如何在火星探测器Kata中停止此循环?

时间:2019-08-14 21:55:38

标签: javascript return break

在此循环中,一旦遇到某种条件(例如遇到障碍物),我将尝试停止循环。

这是有问题的代码:

function moveForward(rover){
  console.log("moveForward was called");
  for(let k = 0; k < obstaclesList.length; k++){
  switch(rover.direction) {
    case "N": if(rover.y <= 0) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else if(rover.y === obstaclesList[k].j) {
      console.log("Obstacle was found!");
      return;
      } else {
      rover.y--;
      console.log("Rover moved up. The position is now " + rover.x + ", " + rover.y);                           
  }
      break;
    case "W": if(rover.x <= 0) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else if(rover.x === obstaclesList[k].i) {
      console.log("Obstacle was found!");
      return;
      } else {
      rover.x--;
      console.log("Rover moved left. The position is now " + rover.x + ", " + rover.y);
  }
      break;
    case "S": if(rover.y >= 10) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else if(rover.y === obstaclesList[k].j) {
      console.log("Obstacle was found!");
      return;
      } else {
      rover.y++;
      console.log("Rover moved down. The position is now " + rover.x + ", " + rover.y);
  }
      break;
    case "E": if(rover.x >= 10) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else if(rover.x === obstaclesList[k].i) {
      console.log("Obstacle was found!");
      return;
      } else {
      rover.x++;
      console.log("Rover moved right. The position is now " + rover.x + ", " + rover.y);         
  }
      break;
  }
  }
  roverMars.travelLog.push("x:" + rover.x + " y:" + rover.y);
}

我在return下的if-else语句中添加了console.log("Obstacle was found!");。但是它没有用,它一直在执行我输入的命令。我尝试用break代替return,但是它也不起作用。帮助吗?

这是其余的代码:

// Rover Object Goes Here
// ======================
let roverMars = {
  direction: "N",
  x: 0,
  y: 0,
  travelLog: ["x:0 y:0"]
};

let testBoard = [ 
  [null,"Rock2",null,null,null,null,null,null,null,null],
  [null,null,null,null,null,null,null,null,null,null],
  [null,null,null,null,null,null,"Bottle",null,null,null],
  [null,null,null,null,null,null,null,null,null,null],
  [null,null,null,null,null,null,null,null,null,null],
  [null,null,null,"Rock",null,null,null,null,null,null],
  [null,null,null,null,null,null,null,null,null,null],
  [null,null,null,null,null,null,null,"Statue",null,null],
  [null,null,null,null,null,null,null,null,null,null],
  [null,null,null,null,null,null,null,null,null,null]
];
let obstaclesList = [];

for(let i = 0; i < testBoard.length; i++){
  for(let j = 0; j < testBoard[i].length; j++) {
    if(testBoard[i][j] !== null) {
      obstaclesList.push({i, j});
    }
  }
}

//console.log(obstaclesList[0].j);

// ======================
function turnLeft(rover){
  console.log("turnLeft was called!");
  switch(rover.direction) {
    case "N": rover.direction = "W";
      console.log("Rover is now facing " + rover.direction);
      break;
    case "W": rover.direction = "S";
      console.log("Rover is now facing " + rover.direction);
      break;
    case "S": rover.direction = "E";
      console.log("Rover is now facing " + rover.direction);
      break;
    case "E": rover.direction = "N";
      console.log("Rover is now facing " + rover.direction);
      break;
  }
}

function turnRight(rover){
  console.log("turnRight was called!");
  switch(rover.direction) {
    case "N": rover.direction = "E";
      console.log("Rover is now facing " + rover.direction);
      break;
    case "W": rover.direction = "N";
      console.log("Rover is now facing " + rover.direction);
      break;
    case "S": rover.direction = "W";
      console.log("Rover is now facing " + rover.direction);
      break;
    case "E": rover.direction = "S";
      console.log("Rover is now facing " + rover.direction);
      break;
  }
}

function moveForward(rover){
  console.log("moveForward was called");
  for(let k = 0; k < obstaclesList.length; k++){
  switch(rover.direction) {
    case "N": if(rover.y <= 0) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else if(rover.y === obstaclesList[k].j) {
      console.log("Obstacle was found!");
      return;
      } else {
      rover.y--;
      console.log("Rover moved up. The position is now " + rover.x + ", " + rover.y);                           
  }
      break;
    case "W": if(rover.x <= 0) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else if(rover.x === obstaclesList[k].i) {
      console.log("Obstacle was found!");
      return;
      } else {
      rover.x--;
      console.log("Rover moved left. The position is now " + rover.x + ", " + rover.y);
  }
      break;
    case "S": if(rover.y >= 10) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else if(rover.y === obstaclesList[k].j) {
      console.log("Obstacle was found!");
      return;
      } else {
      rover.y++;
      console.log("Rover moved down. The position is now " + rover.x + ", " + rover.y);
  }
      break;
    case "E": if(rover.x >= 10) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else if(rover.x === obstaclesList[k].i) {
      console.log("Obstacle was found!");
      return;
      } else {
      rover.x++;
      console.log("Rover moved right. The position is now " + rover.x + ", " + rover.y);         
  }
      break;
  }
  }
  roverMars.travelLog.push("x:" + rover.x + " y:" + rover.y);
}

function moveBackward(rover){
  console.log("moveBackward was called");
  
  switch(rover.direction) {
    case "N": if(rover.y >= 10) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else {
      rover.y++;
      console.log("Rover moved down. The position is now " + rover.x + ", " + rover.y);                           
  }
      break;
    case "W": if(rover.x >= 10) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else {
      rover.x++;
      console.log("Rover moved right. The position is now " + rover.x + ", " + rover.y);
  }
      break;
    case "S": if(rover.y <= 0) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else {
      rover.y--;
      console.log("Rover moved up. The position is now " + rover.x + ", " + rover.y);
  }
      break;
    case "E": if(rover.x <= 0) { 
      console.log("You can't place the rover outside of the 10x10 grid!");
      } else {
      rover.x--;
      console.log("Rover moved left. The position is now " + rover.x + ", " + rover.y);         
  }
      break;
  }
  roverMars.travelLog.push("x:" + rover.x + " y:" + rover.y);
}

function commandments(roverlist) {
  let passRegex = /[lrfb]/g;
  var passResult = roverlist.match(passRegex);
  for(let i = 0; i < passResult.length; i++) {
    switch(roverlist[i]) {
      case "l": turnLeft(roverMars);
        break;
      case "r": turnRight(roverMars);
        break;
      case "f": moveForward(roverMars);
        break;
      case "b": moveBackward(roverMars);
        break;
    }
  }
  //console.log("passResult: " + passResult);
}
commandments("rfffr");
//turnLeft(roverMars);
//turnRight(roverMars);
//moveForward(roverMars);
//console.log(roverMars.travelLog);

该链接在哪个位置:https://codepen.io/kikibres/pen/PMaoYO

1 个答案:

答案 0 :(得分:0)

命名循环并中断循环

function moveForward(rover) {
  console.log("moveForward was called");
  obstacleListLoop: for (let k = 0; k < obstaclesList.length; k++) {
    switch (rover.direction) {
      case "N":
        if (rover.y <= 0) {
          console.log("You can't place the rover outside of the 10x10 grid!");
        } else if (rover.y === obstaclesList[k].j) {
          console.log("Obstacle was found!");
          break obstacleListLoop;
        } else {
          rover.y--;
          console.log(
            "Rover moved up. The position is now " + rover.x + ", " + rover.y
          );
        }
        break;
      case "W":
        if (rover.x <= 0) {
          console.log("You can't place the rover outside of the 10x10 grid!");
        } else if (rover.x === obstaclesList[k].i) {
          console.log("Obstacle was found!");
          break obstacleListLoop;
        } else {
          rover.x--;
          console.log(
            "Rover moved left. The position is now " + rover.x + ", " + rover.y
          );
        }
        break;
      case "S":
        if (rover.y >= 10) {
          console.log("You can't place the rover outside of the 10x10 grid!");
        } else if (rover.y === obstaclesList[k].j) {
          console.log("Obstacle was found!");
          break obstacleListLoop;
        } else {
          rover.y++;
          console.log(
            "Rover moved down. The position is now " + rover.x + ", " + rover.y
          );
        }
        break;
      case "E":
        if (rover.x >= 10) {
          console.log("You can't place the rover outside of the 10x10 grid!");
        } else if (rover.x === obstaclesList[k].i) {
          console.log("Obstacle was found!");
          break obstacleListLoop;
        } else {
          rover.x++;
          console.log(
            "Rover moved right. The position is now " + rover.x + ", " + rover.y
          );
        }
        break;
    }
  }
  roverMars.travelLog.push("x:" + rover.x + " y:" + rover.y);
}

但是,您的代码中有错误(并且质量还有一定的提高空间)。在moveForward中,您遍历障碍,并为每个障碍移动一次。这是moveForward的一个版本,它可以移动一次并具有更好的可读性,并且更接近于惯用的Javascript。请注意,我们不再需要脱离嵌套循环。另请注意,Array.some第一次中断该方法对元素的评估为true的情况(即我们的第一次碰撞)。我建议您以相同的样式重写其他三个move函数,甚至最好将它们合并为一个函数。祝你好运!

const roverMars = {
  direction: "N",
  x: 1,
  y: 2,
  travelLog: ["x:0 y:0"]
};

const testBoard = [
  [null, "Rock2", null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, "Bottle", null, null, null],
  [null, null, null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null, null, null],
  [null, null, null, "Rock", null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, "Statue", null, null],
  [null, null, null, null, null, null, null, null, null, null],
  [null, null, null, null, null, null, null, null, null, null]
];

const obstacleList = testBoard.reduce(
  (acc, row, y) =>
    acc.concat(
      row
        .map((column, x) => (column === null ? null : x))
        .filter(x => x !== null)
        .map(x => ({ x, y }))
    ),
  []
);

console.log(`Obstacles: ${obstacleList.map(({ x, y }) => `x: ${x} y: ${y}`).join(', ')}`)

function moveForward(rover) {
  const crashedWithObstacle = ({ x: roverX, y: roverY }) => ({ x, y }) =>
    roverX === x && roverY === y;
  const newPosition = { x: rover.x, y: rover.y };

  let moveDirection;
  switch (rover.direction) {
    case "N":
      newPosition.y--;
      moveDirection = "up";
      break;
    case "E":
      newPosition.x++;
      moveDirection = "right";
      break;
    case "S":
      newPosition.y++;
      moveDirection = "down";
      break;
    case "W":
      newPosition.x--;
      moveDirection = "left";
      break;
  }

  if (
    newPosition.x < 0 ||
    newPosition.x > 9 ||
    newPosition.y < 0 ||
    newPosition.y > 9
  ) {
    console.log("You can't place the rover outside of the 10x10 grid!");
  } else if (obstacleList.some(crashedWithObstacle(newPosition))) {
    console.log("Obstacle was found!");
  } else {
    rover.x = newPosition.x;
    rover.y = newPosition.y;
    console.log(
      `Rover moved ${moveDirection}. The position is now ${rover.x}, ${rover.y}`
    );
  }
  roverMars.travelLog.push(`x:${rover.x} y:${rover.y}`);
}

moveForward(roverMars);
moveForward(roverMars);