如何获得TypeScript Array.map()返回与VanillaJS相同的结果?

时间:2018-09-29 08:51:37

标签: javascript arrays typescript

在Angular6应用程序中,我正在制作Conway的生活游戏。我试图生成类实例的n x m二维数组。在vanillaJS中,我将其用作:

generateInitialState(bias) {
    return [...Array(this.rows)]
        .map((a, i) => [...Array(this.columns)]
            .map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead')));
}

这将生成一个长度为this.rows的数组,其中包含由Cell类的(n = this.columns)个实例填充的数组。例如。当this.rows = this.columns = 4时(从控制台):

[ [ Cell { x: 0, y: 0, state: 'alive' },
        Cell { x: 1, y: 0, state: 'dead' },
        Cell { x: 2, y: 0, state: 'alive' },
        Cell { x: 3, y: 0, state: 'dead' } ],
      [ Cell { x: 0, y: 1, state: 'alive' },
        Cell { x: 1, y: 1, state: 'alive' },
        Cell { x: 2, y: 1, state: 'dead' },
        Cell { x: 3, y: 1, state: 'dead' } ],
      [ Cell { x: 0, y: 2, state: 'alive' },
        Cell { x: 1, y: 2, state: 'alive' },
        Cell { x: 2, y: 2, state: 'alive' },
        Cell { x: 3, y: 2, state: 'dead' } ],
      [ Cell { x: 0, y: 3, state: 'dead' },
        Cell { x: 1, y: 3, state: 'alive' },
        Cell { x: 2, y: 3, state: 'alive' },
        Cell { x: 3, y: 3, state: 'alive' } ] ] 

在vanillaJS中,它可以正常工作并根据需要生成Array。但是,上面的Typescript代码仅返回一个长度为this.rows的空数组。 TypeScript似乎可以将其编译为:

function generateInitialState(bias) {
var _this = this;
return Array(this.rows).slice().map(function (a, i) { return Array(_this.columns).slice().map(function (b, j) { return new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead'); }); });
}

我如何使它在TypeScript中工作?

完整代码

class Game {
  constructor(columns, rows, randomBias){
    this.columns = columns; 
    this.rows = rows;
    this.randomBias = randomBias;
    this.cells = this.generateInitialState(this.randomBias);
  }
  /* Content omitted for brevity */
  generateInitialState(bias) {
    return [...Array(this.rows)]
      .map((a, i) => [...Array(this.columns)]
        .map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead')));
  }
}
class Cell{
  constructor(x, y, state){
    this.x = x;
    this.y = y;
    this.state = state;
  }
}
let a = new Game(4, 4, 0.5);
console.log(a.cells);

1 个答案:

答案 0 :(得分:2)

问题所在是如何初始化指定大小的数组。当您这样做时:

[...Array(this.rows)]

它被编译为Array(this.rows).slice(),该值不会产生任何值,因为该数组填充有“空洞”,这与您插入的undefined值填充的数组不同原始(未编译)版本。 map不处理孔。

改为尝试Array.from({ length: this.rows })

function generateInitialState(bias) {
  return Array.from({ length: this.rows })
    .map((a, i) => Array.from({ length: this.columns })
      .map((b, j) => new Cell(j, i, (Math.round(Math.random() * 1000) < (1000 * bias)) ? 'alive' : 'dead')));
}