打字稿:未捕获的类型错误,无法读取未定义的 属性 "push"

Typescript: Uncaught typeError, Cannot read property "push" of undefined

private readonly lives: number = 5;   

public loadLifeImages() {
    var ammount: Array<any>;
    for (var i = 0; i < this.lives; i++) {
        ammount.push(i);
    }
    ammount.forEach((v, i) => {
        console.log(this.lives);
        console.log(i);
        var newLifeImage = new Image();
        newLifeImage.src = './assets/images/SpaceShooterRedux/PNG/UI/PlayerLife1_blue.png';
        newLifeImage.onload = () => {
            this.ctx.drawImage(newLifeImage, i * 50, 50, 30, 30);
        }
    })
}

我试图将这些数字推送到 Typescript 中的这个数组,因此我可以使用 for each 循环将图像放在我的 canvas 上,但是它给出了错误 'cannot read property "push" of undefined' I知道它有点双重,但我真的想不出任何其他方法来做到这一点。有人能弄清楚它是什么吗?提前致谢!

这可以通过像这样初始化 ammount 来解决:

var ammount: Array<any> = [];

这是因为仅键入 var ammount: Array<any> 不会为 ammount 赋值,因此它变为 undefined(所有 javascript 变量的默认值)。 = [] 将变量初始化为空数组。

但是,我想指出,从您这里的代码来看,没有充分的理由创建一个新数组并将值推入其中。相反,您可以将 forEach 逻辑放在 for 循环中。