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

时间:2013-09-01 20:16:06

标签: javascript function arguments multidimensional-array

我正在进行一项练习,以重新创造康威的生命游戏,我有一个基本的策略,而且我仍然非常关注"使它工作"阶段,所以我知道这看起来很有趣。

我现在遇到的问题是我尝试迭代2-D阵列,每次调用确定细胞是活着还是死亡的函数。这是返回' undefined'的最后一段代码。为' col'。

在循环外部调用函数时(函数分配给row和col)。

但是,当我尝试调用循环内的函数时,我得到了未定义的值。我假设这是一个范围问题,但我不确定如何解决它。

以下是代码:

// 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);
        }
    }                            

1 个答案:

答案 0 :(得分:1)

您的代码存在一些问题:

  • 整个代码中的几次调用都会拒绝未声明的变量rowcol
  • 循环将row声明为全局(不是“错误”,但不是很好的做法)
  • deadCellsLiveOrDie的方法调用输入错误。
  • getNeighbors方法不进行边界检查,因此您将超出范围。

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