var groups = new Truck([
{id: num, content: `Truck ${num}`}
]);
In a constructor, I am trying to increment the whole object inside an array on a button click. I also want to increase the Number(num) of the id and content. And, I want to use a button for this whole process, when I click a button an array should add one more object inside itself along with the number incremented, like this:
var groups = new Truck([
{id: 1, content: `Truck 1`},
{id: 2, content: `Truck 2`},
{id: 3, content: `Truck 3`},
{id: 4, content: `Truck 4`}
]);
Use the class constructor to declare an id and an array.
Declare an add method that creates a new object based on the current id, pushes it in to the array, and then increments the id.
Create an instance of Truck.
Create a button, and attach a listener to it that calls a function that calls add on the instance, and then logs it.
class Truck {
constructor() {
this.id = 1;
this.arr = [];
}
add() {
this.arr.push({
id: this.id,
content: `Truck ${this.id}`
});
++this.id;
}
}
const group = new Truck();
const button = document.querySelector('button');
button.addEventListener('click', handleClick, false);
function handleClick() {
group.add();
console.log(group);
}
<button>Add new object</button>