How to update argument's value of list in JavaScript

Viewed 32

I have a list with three empty objects like:

TimePickerList =[{},{},{}];

For example, I want to add 1 and 2 to the first argument of this list like this:

TimePickerList[0].push("1") // I know it's wrong and I can't use push like this.
TimePickerList[0].push("2")

And i want to get this:

TimePickerList =[{"1","2"},{},{}];

Is there any way to do this? I mean, can I update an argument's value?

2 Answers

Not really. I think you looking for an array with arrays.

const t = [[],[]];

t[0].push(1);
t[0].push(2)
console.log(t)

You can update values stored in arrays like such:


TimePickerList = [{}, {}, {}];

TimePickerList[0].a = 1;

console.log(TimePickerList)
   // [{ a: 1 }, {}, {}]

The reason it wasn't working for you is because you were trying to push a value to an object. If you want to push values then push to an array, therefore using square brackets [] instead of curly braces {}.

Related