TypeScript add Object to array with push
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) {}
}
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);