似乎无法在javascript中添加两个整数?

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)

Zah*_*med 5

原因有两个:

  1. 在JavaScript中,变量是松散类型的,这就是为什么int在算术运算之前解析它的好处.

    尝试:

    console.log(game.cells[parseInt(i,10) + parseInt(grid.cellsY,10)]);
    
    Run Code Online (Sandbox Code Playgroud)
  2. 您正在尝试访问阵列,您需要检查parseInt(i,10) + parseInt(grid.cellsY,10)阵列中是否 存在索引.

  • JavaScript变量根本没有输入.由于`+`用于添加数字和连接字符串,因此在执行添加之前将可能的字符串显式转换为数字是个好主意. (2认同)