问题描述
我在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,您可能需要明确检查 undefined 而不是使用 !
。