如何用二维数组实例化一个类对象?

时间:2018-04-19 18:29:02

标签: javascript arrays class instantiation

我正在尝试使用二维数组来实例化一个对象,但以下代码似乎不起作用:

      $.each(series, function (i, s) {
          debugger;
          $.each(s.points, function (j, p: any) {
            debugger;
            topPosition.push(p);
          });
        });


topPosition[index].dataLabel.translateY

https://jsbin.com/worepeb/edit?js,console

1 个答案:

答案 0 :(得分:2)

您需要初始化子数组才能填充数字 - this.board[i] = [];



class Board {
  constructor(row,col){
    this.board=[];
    for (var i=0; i<row; i++){
      this.board[i] = []; // init this.board[i]
      for (var y=0; y<col; y++){
        this.board[i][y]=0;
      }
    }
  }
}

var board = new Board(10,10);

console.log(board);
&#13;
&#13;
&#13;

您也可以使用Array.from()来启动董事会:

&#13;
&#13;
class Board {
  constructor(row,col){
    this.board = Array.from({ length: row }, () => 
      Array.from({ length: col }, () => 0)
    );
  }
}

const board = new Board(10,10);

console.log(board);
&#13;
&#13;
&#13;