Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot seem to add two integers in javascript?

Im building John Conways game of life with HTML5 canvas. It has a gameOfLife object which contains an array with all the cells and their states (dead/alive). Here is the code that builds a cell:

function cell(x,y){
    this.x = x;
    this.y = y;
    this.isAlive = false;
}

I am exploring ways of checking a cells surrounding cells states. As I understand, one way is to iterate through the array and find a cell with coordinates that match as being around the currently checked cell.

I was thinking of going about a different way. By adding and subtracting the number of cells (with small variations of +1 and -1) on the Y (and the X) axis from the index of the cell being evaluated, you should be able to come up with the index of any top left, left, bottom left, top right, right, bottom right cell.

I haven't been able to test this idea though, as it doesn't let me get the desired index:

So, in my update loop:

//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?!

}
like image 739
styke Avatar asked Apr 23 '13 17:04

styke


People also ask

How do you add two numbers in JavaScript using functions?

const num1 = parseInt(prompt('Enter the first number ')); const num2 = parseInt(prompt('Enter the second number ')); Then, the sum of the numbers is computed. const sum = num1 + num2; Finally, the sum is displayed.

Which method can be used to get an integer between two values in JavaScript?

Math. random() * (max-min) + min); Generate a random integer between two numbers min and max (both min and max are inclusive).

Why is 0 not a number in JavaScript?

In JavaScript “0” is equal to false because “0” is of type string but when it tested for equality the automatic type conversion of JavaScript comes into effect and converts the “0” to its numeric value which is 0 and as we know 0 represents false value. So, “0” equals to false.


1 Answers

There can be two reasons:

  1. In JavaScript variables are of loose-type that's why its good to parse int before arithmetic operation.

    try:

    console.log(game.cells[parseInt(i,10) + parseInt(grid.cellsY,10)]);
    
  2. You are trying to access an array, you need to check whether parseInt(i,10) + parseInt(grid.cellsY,10) index exist in your array or not.

like image 131
Zaheer Ahmed Avatar answered Sep 21 '22 08:09

Zaheer Ahmed