TypeScript使用push将Object添加到数组

Joh*_*nes 18 arrays typescript

我只想将类的对象(Pixel)添加到数组中.

export class Pixel {
  constructor(x: number, y: number) {}
}
Run Code Online (Sandbox Code Playgroud)

该类具有以下属性:

pixels: Pixel[] = [];
Run Code Online (Sandbox Code Playgroud)

以下代码对我来说看起来合乎逻辑,但不会将实际对象推送到我的数组像素.

this.pixels.push(new Pixel(x, y));
Run Code Online (Sandbox Code Playgroud)

只有这个有效:

var p = {x:x, y:y};
this.pixels.push(p);
Run Code Online (Sandbox Code Playgroud)

有人可以解释一下为什么上述说法不起作用?

Mot*_*tti 32

如果您的示例代表您的真实代码,问题不在于push,那就是您的构造函数不执行任何操作.

您需要声明并初始化xy成员.

明确:

export class Pixel {
    public x: number;
    public y: number;   
    constructor(x: number, y: number) {
        this.x = x;
        this.y = y;
    }
}
Run Code Online (Sandbox Code Playgroud)

或隐含地:

export class Pixel {
    constructor(public x: number, public y: number) {}
}
Run Code Online (Sandbox Code Playgroud)