You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中lastPosition变量提前被修改的问题排查求助

问题排查:地图位置校验逻辑异常

代码功能说明

这段代码用于校验position变量是否处于map数组记录的有效地块上:

  • 若在地图范围内,输出地图信息并将lastPosition更新为当前position
  • 若不在地图范围内,将position重置为lastPosition

问题现象

lastPosition变量似乎在被代码访问前就已被修改——而且是在进入检查位置的for循环(代码中唯一对该变量赋值的逻辑)之前就发生了变化,导致用户可以移出地图范围。控制台无报错,已尝试添加大量console.log调试、重构代码,但仍无法定位问题根源。

完整代码

JavaScript 代码

//map variable
const map = [
  [
    [0, 0],
    ['this is room 1']
  ],
  [
    [0, 1],
    ['this is room 2']
  ]
];
var position = [0, 0];
var lastPosition = [0, 0];

//run the script when enter is pressed
document.onkeydown = function(e) {
  e = e || window.event;
  var key = e.which || e.keyCode;
  if (key === 13) {
    run();
  }
}

//main run function
function run() {
  console.log(map);
  //get input from text box
  input = document.getElementById('input').value;
  if (input == '') {
    return;
  }
  console.log(input);

  interpreter();
}

//interprets the input in the box
function interpreter() {
  if (input == 'up') {
    position[1] += 1;
    accessMap()
  } else if (input == 'down') {
    position[1] -= 1;
    accessMap()
  } else if (input == 'right') {
    position[0] += 1;
    accessMap()
  } else if (input == 'left') {
    position[0] -= 1;
    accessMap()
  }
}

function accessMap() {
  console.log(position);
  console.log(lastPosition);
  var positionInfo = position.toString();
  var positionTest = 0;
  console.log('before: ' + positionTest);
  //checks if your position is in the map by turning arrays into strings and comparing them
  for (i = 0; i < map.length; i++) {
    mapInfo = map[i][0].toString();
    console.log('Map info: ' + mapInfo);
    console.log('Position info: ' + positionInfo);
    //if inside map
    if (positionInfo == mapInfo) {
      console.log('in map');
      positionTest = 1;
      lastPosition = position;
      console.log('in map test: ' + positionTest);
    }
  }
  console.log('after: ' + positionTest);
  //if not inside map
  if (positionTest != 1) {
    console.log('not in map');
    position = lastPosition;
    console.log('out map test: ' + positionTest);
  }
  console.log(position);
  console.log(lastPosition);
}

HTML 代码

<input id="input" type="text">

补充说明

当前HTML嵌入JS的方式比较特殊,但这是项目硬性要求,且单独拆分JS文件后问题依旧。扩大map范围也未改变问题现象。

内容的提问来源于stack exchange,提问作者ChickenStripsMan5445

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 19:07:25