Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 998
Johannes Avatar asked Jul 06 '16 13:07

Johannes


People also ask

How do you push an object into an array of objects in TypeScript?

To push an object to an array: Set the type of the array to Type[] . Set the type of the object to Type . Use the push() method to push the object to the array.

Can you push an object into an array?

To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.

How do you push in TypeScript?

Overview. We push an element to an array in TypeScript, similarly to pushing an element in JavaScript. We use the push() method for this purpose. In TypeScript, we can push or add one or more elements to the end of an Array.

How do you dynamically add an element to an array in TypeScript?

There are two ways to dynamically add an element to the end of a JavaScript array. You can use the Array. prototype. push() method, or you can leverage the array's “length” property to dynamically get the index of what would be the new element's position.


1 Answers

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) {} } 
like image 67
Motti Avatar answered Nov 07 '22 20:11

Motti