二维数组中未定义的未定义

Undefined of undefined in 2d array

我在 javascript 中有一个二维数组“网格”,我想防止“未定义的未定义错误”并在第一个数组的索引小于 0 时返回一个简单的“未定义” ,这是我的脚本:

      let top = grid[this.posX][this.posY - 1];
      let right = grid[this.posX + 1][this.posY];
      let bottom = grid[this.posX][this.posY + 1];
      let left = grid[this.posX - 1][this.posY];

      if (top && !top.visited) neighbors.push(top);
      if (right && !right.visited) neighbors.push(right);
      if (bottom && !bottom.visited) neighbors.push(bottom);
      if (left && left && !left.visited) neighbors.push(left);

这是可行的解决方案,但我想知道是否有更好的方法来使用更少的代码:

   let left, right, top, bottom;

      let xm = this.posX - 1;
      let xp = this.posX + 1;
      let ym = this.posY - 1;
      let yp = this.posY + 1;

      if (xm < 0) {
        left = undefined;
      } else {
        left = grid[xm][this.posY];
      }

      if (xp > rows) {
        right = undefined;
      } else {
        right = grid[xp][this.posY];
      }

      if (ym < 0) {
        top = undefined;
      } else {
        top = grid[this.posX][ym];
      }

      if (yp > cols) {
        bottom = undefined;
      } else {
        bottom = grid[this.posX][yp];
      }

提前致谢

您可以在此代码之前添加一个检查以检测 posX 越界。

if(!grid[this.posX - 1] || !grid[this.posX + 1])
  return undefined;

我不确定你的网格包含什么,如果你的网格可能包含 0 也是虚假的,你可能想要明确检查未定义而不是使用 !