[英]TypeScript add Object to array with push
I would just like to add an object of an class (Pixel) to an array. 我只想将类的对象(Pixel)添加到数组中。
export class Pixel {
constructor(x: number, y: number) {}
}
The class has the following attribute: 该类具有以下属性:
pixels: Pixel[] = [];
The following code looks logical for me, but does not push the actual objects to my array pixels. 以下代码对我来说看起来合乎逻辑,但不会将实际对象推送到我的数组像素。
this.pixels.push(new Pixel(x, y));
Only this works: 只有这个有效:
var p = {x:x, y:y};
this.pixels.push(p);
Could anybody explain me why the above statement does not work? 有人可以解释一下为什么上述说法不起作用?
If your example represents your real code, the problem is not in the push
, it's that your constructor doesn't do anything. 如果您的示例代表您的真实代码,则问题不在于push
,而是您的构造函数不执行任何操作。
You need to declare and initialize the x
and y
members. 您需要声明并初始化x
和y
成员。
Explicitly: 明确:
export class Pixel {
public x: number;
public y: number;
constructor(x: number, y: number) {
this.x = x;
this.y = y;
}
}
Or implicitly: 或隐含地:
export class Pixel {
constructor(public x: number, public y: number) {}
}
class PushObjects {
testMethod(): Array<number> {
//declaration and initialisation of array onject
var objs: number[] = [1,2,3,4,5,7];
//push the elements into the array object
objs.push(100);
//pop the elements from the array
objs.pop();
return objs;
}
}
let pushObj = new PushObjects();
//create the button element from the dom object
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () {
alert(pushObj.testMethod());
}
document.body.appendChild(btn);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.