javascript 2D数组迭代返回未定义的函数参数

javascript 2D array iteration returning undefined function args

本文关键字:函数 参数 未定义 返回 2D 数组 迭代 javascript      更新时间:2023-09-26

我正在进行一项练习,以重现康威的《人生游戏》,我有一个基本的策略,我仍然处于"让它发挥作用"的阶段,所以我知道这看起来很有趣。

我现在遇到的问题是,我试图迭代二维数组,每次都调用确定细胞存活还是死亡的函数。这是为"col"返回"undefined"的最后一个代码块。

函数在循环外调用时工作(变量分配给行和列)。

然而,当我尝试调用循环中的函数时,我会得到未定义的值。我认为这是一个范围问题,但我不确定具体如何解决

这是代码:

// this is the world that is being calculated
var world = [
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 1, 0],
    [0, 1, 0, 1, 0],
    [0, 0, 0, 0, 0]
];
// this is where the new calculated values are stored until they are ready to
// be transferred back to the first array: world
var tempWorld = [
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0]
];


function getNeighbors(row, col) {
  // variables that get the values of the 8 neighboring cells
  var currentCell = world[row][col];
  var upperLeftCorner = world[row - 1][col - 1];
  var above = world[row - 1][col];
  var upperRightCorner = world[row - 1][col + 1];
  var left = world[row][col - 1];
  var right = world[row][col + 1];
  var bottomLeft = world[row + 1][col - 1];
  var bottom = world[row + 1][col];
  var bottomRight = world[row + 1][col + 1];    
    // this variable adds the neighboring cells together
  var totalNumberOfNeighbors = upperLeftCorner + above + upperRightCorner + left + right + bottomLeft + bottom + bottomRight   
  return totalNumberOfNeighbors;
};
// test to confirm that getNeighbors is working
console.log("value of getNeighbors is: " + getNeighbors(row, col));
function deadCellsLiveOrDie (row, col) {
  // Rule to make dead cells living
  if (world[row][col] === 0) {
    if (getNeighbors(row, col) === 3) {
      tempWorld[row][col] = 1;
    }
  }
};
deadCellsLiveOrDie(row, col);
livingCellsLiveOrDie(row, col);
function livingCellsLiveOrDie (row, col) {
  // Rule to determine if living cells die or live
  if (world[row][col] === 1) {
    if ((getNeighbors(row, col) === 2) || (getNeighbors(row, col) === 3)) {
      tempWorld[row][col] = 1;
    } else tempWorld[row][col] = 0 
  }
};
// test to confirm that rules of life work for a cell
console.log("tempWorld row, col is: " + tempWorld[row][col]);

// iterate over the 2-D array
for (row = 0; row < world.length; ++ row)
    {
        var col;
        for (col = 0; col < world[row].length; ++ col) {
        deadCellsLiverOrDie(row, col);
        livingCellsLiveOrDie(row, col);
        }
    }                            

您的代码出现了一些问题:

  • 整个代码中的几个调用引用了未声明的变量rowcol
  • 循环将row声明为全局(不是"错误",但不是好的做法)
  • deadCellsLiveOrDie的方法调用类型错误
  • getNeighbors方法不进行边界检查,因此会超出范围

可以在此处找到(快速)修复版本:http://jsfiddle.net/Eakcm/