我只想将一个类(像素)的对象添加到数组中。
export class Pixel {
constructor(x: number, y: number) {}
}
该类具有以下属性:
pixels: Pixel[] = [];
以下代码对我来说看起来合乎逻辑,但是没有将实际对象推送到我的数组像素中。
this.pixels.push(new Pixel(x, y));
仅此有效:
var p = {x:x, y:y};
this.pixels.push(p);
谁能解释我为什么上述说法不起作用?
如果您的示例代表您的真实代码,则问题不在push
,这是您的构造函数没有执行任何操作。
您需要声明和初始化x
和y
成员。
明确地:
export class Pixel {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
或隐式地:
export class Pixel {
constructor(public x: number, public y: number) {}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句