Johannes
Johannes

Reputation: 2812

TypeScript add Object to array with push

I would just like to add an object of an class (Pixel) to an array.

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?

Upvotes: 37

Views: 246465

Answers (2)

satish hiremath
satish hiremath

Reputation: 127

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

Upvotes: 2

Motti
Motti

Reputation: 114725

If your example represents your real code, the problem is not in the push, it's that your constructor doesn't do anything.

You need to declare and initialize the x and y members.

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

Upvotes: 39

Related Questions