【发布时间】:2013-09-04 22:17:51
【问题描述】:
我正在通过一个练习来重现康威的人生游戏,我有一个基本策略,但我仍处于“让它发挥作用”阶段,所以我知道这看起来很有趣。
我现在遇到的问题是我正在尝试遍历二维数组,并且每次都调用确定细胞是生还是死的函数。这是为 'col' 返回 'undefined' 的最后一段代码。
函数在循环外调用时起作用(变量分配给 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);
}
}
【问题讨论】:
-
现在您的代码无法执行,因为您在其中有几个调用使用了从未初始化过的
row和col变量。此外,最后一个块中的循环会将row初始化为全局。此外,您在循环中拼错了deadCellsLiveOrDie。 -
另外,您的
getNeighbors方法没有任何边界检查,即它将尝试访问数组索引-1。 -
这是您要找的吗? jsfiddle.net/Eakcm(可以做得更漂亮,但我试图坚持你已经拥有的)
-
你 === 最好的!我正在尝试接受您的回答,但没有看到您的 cmets 旁边的复选框...
-
我必须把它写成答案,而不是评论。我会这样做,然后你可以接受。 /编辑:完成
标签: javascript function arguments multidimensional-array