While循环边界中的2D数组

时间:2017-08-28 13:43:51

标签: javascript arrays while-loop indexoutofboundsexception

我在解决如何使用2D数组和while循环方面遇到了一些问题。

以下是相关的代码段:

while (
    table[i - count][j] === 0 ||
    table[i + count][j] === 0 ||
    table[i][j - count] === 0 ||
    table[i][j + count] === 0
) { ... count++; }

运行我的代码段时出现以下错误:

  

TypeError:无法读取属性' 0'未定义的

现在我明白这种情况正在发生,因为如果我有i = 0,那么table[i - count][j]会检查table[-1][j]。显然这不应该工作,但这是我实施的while循环的目的。

我希望代码在此2D数组的边缘超出范围时停止运行(如上所述)或者元素的值为0。

目前,当我需要它来停止并在while循环之后继续执行代码时,它会给我错误。我该如何解决这个问题?

修改

是的,我确定我希望这些条件为&&。主要问题是i -count可能导致负数。或者i + count可能会导致数组超出范围。

如何在这个while循环中处理那些超出界限的事件?

4 个答案:

答案 0 :(得分:0)

你需要在访问其密钥之前使数组存在,并且检查0或未定义是无关紧要的,因为它们都是 falsy

while(
 (table[i - count] || [])[j] &&
 (table[i + count] || [])[j] &&
 (table[i] || [])[j + count] &&
 (table[i] || [])[j - count]
) count++;

答案 1 :(得分:0)

假设您的条件由"and"连接 只需添加额外条件即可检查数组索引的有效值/边界

while (
    table[i - count][j] !== 0 && table[i - count][j] !== undefined &&
    table[i + count][j] !== 0 && table[i + count][j] !== undefined &&
    table[i][j - count] !== 0 && table[i][j - count] !== undefined &&
    table[i][j + count] !== 0 && table[i][j + count] !== undefined &&
    i - count > 0 &&
    j - count > 0
) { ... count++; }

答案 2 :(得分:0)

对,我找到了解决方案。它总体上可能不是最优的,但是我正在做的事情是完美的:

while (
    i - count >= 0 &&
    j - count >= 0 &&
    i + count < table.length &&
    j + count < table[i].length
) {
    if (
        table[i - count][j] === 0 ||
        table[i + count][j] === 0 ||
        table[i][j - count] === 0 ||
        table[i][j + count] === 0
    ) return prod;

    prod *= (
        table[i - count][j] *
        table[i + count][j] *
        table[i][j - count] *
        table[i][j + count]
    );

    count++;
}

答案 3 :(得分:0)

如前所述,使用我建议使用返回布尔值的函数。这将保持您的循环清洁,您可以选择具有更具描述性的条件代码。

function validate(array, i, j, count){
  // To cover case when either variable is 0
  if(i && j){
    let prev = array[i - count];
    let next = array[i + count];
    let curr = array[i];

    return (
      (j < prev.length && prev[j] === 0) ||
      (j < next.length && next[j] === 0) ||

      // Since we have already added a check for value !== 0, 
      // we just have to check for out of bound here.
      (j < curr.length -1) && (
        curr[j - count] === 0 ||
        curr[j + count] === 0
      )
    )
  }
  return false;
}
while (validate(table, i, j, count)) { ... count++; }