繁体   English   中英

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

[英]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,这也是虚假的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM