37

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?

1
  • 1
    your code is fine and is working well when I try it. It must be something else that causes the problem. Please include the real code that is problematic along with the error message Commented Jul 6, 2016 at 13:48

2 Answers 2

39

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) {}
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. Indeed the constructor was wrong. IMO the IDE could give me a warning on this issue, because I doubt anybody want that behavior. :-)
If you want to use ES6 version filter like: this.pixels.filter(e => e.x === value); you'll need to use the 'Explicitly' model as shown.
@phanf I don't think that's correct, the generated javascript is identical
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 Comments

Hello, please learn how to format code, it's easy. Also would be nice to add some comment, for example, what Your code does.
better to use const than var

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.