简体   繁体   English

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

[英]Undefined of undefined in 2d array

i have a 2D array "grid" in javascript, i want to prevent "the undefined of undefined error " and returning a simple "undefined", when the index of the first array is less than 0, this is my script:我在 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);

here is the solution that works but i want to nkow if there is a better way to do it with less code:这是有效的解决方案,但我想知道是否有更好的方法用更少的代码来完成它:

   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];
      }

Thanks in advance提前致谢

You could add a check just before this code to detect out of bounds on posX.您可以在此代码之前添加一个检查以检测 posX 上的越界。

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

I'm not sure what your grid contains, you might want to explicitly check for undefined instead of using the !我不确定您的网格包含什么,您可能想要明确检查未定义而不是使用! if you grid could contain 0s which are also falsy.如果您的网格可以包含 0,这也是虚假的。

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

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