[英]How do I get TypeScript Array.map() to return the same as VanillaJS?
在我的Angular6应用中,我正在制作Conway的生活游戏。 我正在尝试生成类实例的nxm二维数组。 在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);
问题所在是如何初始化指定大小的数组。 执行此操作时:
[...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')));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.