即使在更改值之后,数组的javascript元素仍保持不变

时间:2017-11-16 14:02:30

标签: javascript html5

我的问题是:

假设这个类,它是我真实代码的一个例子:



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]);
&#13;
&#13;
&#13;

显示以下输出:

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

矩阵被修改但返回到值之前。 我该怎么办? (注意我不熟悉javascript但使用C ++之类的语言)

1 个答案:

答案 0 :(得分:1)

我不明白出了什么问题。我在你的代码中添加了播放器对象。

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]);