TypeScript 使用 push 方法将对象添加到数组

38
我只想将一个类的对象(Pixel)添加到一个数组中。
export class Pixel {
  constructor(x: number, y: number) {}
}

这个类具有以下属性:

pixels: Pixel[] = [];

以下代码在我看来似乎很合理,但并没有将实际对象推入我的数组 pixels 中。

this.pixels.push(new Pixel(x, y));

只有这个起作用:

var p = {x:x, y:y};
this.pixels.push(p);

有人能解释一下为什么上面的陈述无效吗?


1
你的代码很好,当我尝试时它能够正常工作。问题一定是由其他原因引起的。请提供有问题的真实代码以及错误信息。 - Nitzan Tomer
2个回答

40

如果您的示例代表了您的真实代码,问题不在于push,而在于您的构造函数没有执行任何操作。

您需要声明并初始化xy成员变量。

明确地说:

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) {}
}

非常感谢。实际上构造函数是错误的。在我看来,IDE应该在这个问题上给我一个警告,因为我怀疑没有人想要那种行为。 :-) - Johannes
如果你想使用ES6版本的filter方法,例如:this.pixels.filter(e => e.x === value); 那么你需要像下面这样明确地指定模型。 - phanf
@phanf 我认为那不正确,生成的 JavaScript 代码是相同的(https://www.typescriptlang.org/play/#src=export%20class%20ExplicitPixel%20%7B%0D%0A%20%20%20%20public%20x%3A%20number%3B%0D%0A%20%20%20%20public%20y%3A%20number%3B%20%20%20%0D%0A%20%20%20%20constructor(x%3A%20number%2C%20y%3A%20number)%20%7B%0D%0A%20%20%20%20%20%20%20%20this.x%20%3D%20x%3B%0D%0A%20%20%20%20%20%20%20%20this.y%20%3D%20y%3B%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0Aexport%20class%20ImplicitPixel%20%7B%0D%0A%20%20%20%20constructor(public%20x%3A%20number%2C%20public%20y%3A%20number)%20%7B%7D%0D%0A%7D) - Motti

2
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);

2
你好,请学习如何格式化代码,这很容易。另外最好添加一些注释,例如,你的代码是做什么的。 - NoAngel
最好使用const而不是var。 - Michael Freidgeim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接