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?
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.
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.
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.
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.
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) {} }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With