javascript element of array stays unchangeable, even after change value

Viewed 81

My problem is this:

Suppose this class, it's an example of my true code:

class TileMap {
    constructor ( w, h ) {
        this.tiles = [];

        // init the matrix
        for (var i = 0; i < h; i++) {
            var a = [];
            for (var j = 0; j < w; j++) {
                a.push(0);
            }
            this.tiles[i] = a;
        }
    }

    setTile (x, y, tile) {
        this.tiles[y][x] = tile;
    }

    doSomething () {
        this.setTile(0, 0, 1);
        this.setTile(0, 1, 2);
    }
}

// What's happening is when I use like this:
var player = {};
player.map = new TileMap(32, 90, 90);

player.map.doSomething();
console.log("before Tile[0][0] = " + player.map.tiles[0][0]);

player.map.setTile(0, 0, 3);
console.log("after Tile[0][0] = " + player.map.tiles[0][0]);

Shows me the follow output:

before Tile[0][0] = 1
after Tile[0][0] = 1

The matrix are modified but turn back to before values. What should I do? (NOTE I'm not familiar with javascript but with language like C++)

1 Answers

I do not understand what is wrong. I added to your code the player object.

class TileMap{
  constructor ( w, h ){
    this.tiles = [];
    //init the matrix
    for (var i = 0; i < h; i++)
    {
      var a = [];
      for (var j = 0; j < w; j++)
        a.push(0);
      this.tiles[i] = a;
    }
  }

  setTile (x, y, tile){
    this.tiles[y][x] = tile;
  }

  doSomething (){
    this.setTile(0,0, 1);
    this.setTile(0,1, 2);
  }
}

//What's happening is when I use like this:
var player = {};
player.map = new TileMap(32,90,90);
player.map.doSomething();
console.log("before Tile[0][0] = "+player.map.tiles[0][0]);
player.map.setTile(0,0, 3);
console.log("after Tile[0][0] = "+player.map.tiles[0][0]);

Related