Saturday, August 18, 2018

JS - split an array string and pass both parts as arguments to a method

So, I've got a method to grab particular DIV from x, y coordinates:

this.getCell = function (x, y){
      this.index = x + y * this.width;
      return this.cells[this.index];
}

I want to use my method with another one:

this.computeCellNextState = function(x, y){

      var nearbies = ['x-1,y-1','x,y-1','x+1,y-1'];
      var splitter = nearbies[0].split(',');

      console.log(this.getCell(splitter[0],splitter[1])); // returns undefined

}

What I want to achieve:

this.getCell(x-1,y-1)

x-1,y-1 are from nearbies[0]

I want to split one string of 'nearbies' and use as 2 parameters.

Solved

'x-1,y-1' etc are just strings, they don't mean anything for getCell. You have to work with actual expressions in computeNextState, e.g.

this.computeCellNextState = function(x, y){

      var nearbies = [[x-1,y-1],[x,y-1],[x+1,y-1]];

      console.log(this.getCell(...nearbies[0]))

}

No comments:

Post a Comment