简体   繁体   中英

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:

      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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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