来自命令的 JS 坐标

问题描述 投票:0回答:2

当我们需要从命令更新坐标数组时,我有一些任务需要解决,如下所示。 当向前 - y 加 1,向后 - y 减 1,右 - x 加 1 和左 - x 减 1 时。但是这里有些东西不能正常工作。

function getLocation(coordinates, commands) {
  // write code here
  let x = coordinates[0]
  let y = coordinates[1]
  //let newCoordinates = [];

    for (let i = 0; i < commands.length; i++) {
     if (i === 'forward' ) {
          y += 1 ;
          }
       if (i === 'back') {
         y -= 1 ;
      }
      if (i === 'right') {
      x +=  1;
      }
      if (i === 'left') {
      x -= 1;
    }

 }
 //newCoordinates.push(x, y)
return coordinates;

}
 console.log(getLocation([0, 0], ['forward', 'forward', 'left']))
javascript coordinates move robot
2个回答
1
投票

循环时您没有访问

commands
数组中的值。目前您正在比较
i
是否为
'forward'
'back'
或任何其他命令。

您应该做的是通过访问值来比较

commands
数组中的每个值。
commands[i] === 'forward'
,等等。

返回

coordinates
数组不会为您提供更新的值,因为修改
x
y
不会更新
coordinates
数组中的值。解决此问题的最简单方法是返回一个包含
x
y
的新数组,如下所示:
return [x, y];

function getLocation(coordinates, commands) {
  let x = coordinates[0]
  let y = coordinates[1]

  for (let i = 0; i < commands.length; i++) {
    if (commands[i] === 'forward') {
      y += 1;
    }
    
    if (commands[i] === 'back') {
      y -= 1;
    }
    
    if (commands[i] === 'right') {
      x += 1;
    }
    
    if (commands[i] === 'left') {
      x -= 1;
    }
  }
  
  return [x, y];
}

console.log(getLocation([0, 0], ['forward', 'forward', 'left']))

我还冒昧地修改了您的函数,以使用 解构赋值 rest 参数 作为示例,说明如何以不同的方式实现该函数。不知道它是否会对您有所帮助,但我假设您仍在学习,这可能会扩展您的知识库。

function getLocation([x, y], ...commands) {
  for (command of commands) {
    if (command === 'forward') {
      y += 1;
    }
    
    else if (command === 'back') {
      y -= 1;
    }
    
    else if (command === 'right') {
      x += 1;
    } 
    
    else if (command=== 'left') {
      x -= 1;
    }
  }
  
  return [x, y];
}

console.log(getLocation([0, 0], 'forward', 'forward', 'left'))


0
投票

您正在使用索引来检查命令,您应该在条件语句中使用数组的值,如下所示

function getLocation(coordinates, commands) {
  let x = coordinates[0]
  let y = coordinates[1]
  let newCoordinates = [];
  
  commands.forEach((command) => {
      if (command === 'forward' ) {
          y += 1 ;
      }
      if (command === 'back') {
         y -= 1 ;
      }
      if (command === 'right') {
        x +=  1;
      }
      if (command === 'left') {
        x -= 1;
      }
  })

  newCoordinates.push(x, y)
  return newCoordinates;

}
 console.log(getLocation([0, 0], ['forward', 'forward', 'left']))

© www.soinside.com 2019 - 2024. All rights reserved.