sty*_*yke 5 javascript arrays indexing jquery integer
我用HTML5画布构建John Conways的生活游戏.它有一个gameOfLife对象,它包含一个包含所有单元格及其状态(死/活)的数组.以下是构建单元格的代码:
function cell(x,y){
this.x = x;
this.y = y;
this.isAlive = false;
}
Run Code Online (Sandbox Code Playgroud)
我正在探索检查细胞状态周围细胞的方法.据我所知,一种方法是遍历数组并找到一个坐标匹配的单元格,该单元格位于当前已检查的单元格周围.
我在考虑采用不同的方式.通过在被评估的单元格的索引上添加和减去Y(和X)轴上的单元格数(具有+1和-1的小变化),您应该能够得出任何顶部的索引左,左,左下,右上,右,右下单元格.
我无法测试这个想法,因为它不能让我得到所需的索引:
所以,在我的更新循环中:
//I know that there is a cell at the index of exampleIndex + cellsY
exampleIndex = 200;
game.getLivingNeighbours(exampleIndex);
function getLivingNeighbours(i){
console.log(i) //Logs an integer
console.log(grid.cellsY) //Logs an integer
console.log(game.cells[i + grid.cellsY]); //Undefined?!
}
Run Code Online (Sandbox Code Playgroud)
原因有两个:
在JavaScript中,变量是松散类型的,这就是为什么int在算术运算之前解析它的好处.
尝试:
console.log(game.cells[parseInt(i,10) + parseInt(grid.cellsY,10)]);
Run Code Online (Sandbox Code Playgroud)您正在尝试访问阵列,您需要检查parseInt(i,10) + parseInt(grid.cellsY,10)阵列中是否
存在索引.