Home > database >  Array is undefined when trying to push into it
Array is undefined when trying to push into it

Time:02-11

I am trying to push into an array some values from a model.

public model: WeekDays[];

WeekDays is an enum of this type

export enum WeekDays {
    Monday,
    Tuesday,
    Wednesday,
    Thursday,
    Friday,
    Saturday,
    Sunday,
}

So i have a save function which should do the following:

public save(){
        this.model.forEach(function (value){
            this.arr.push(WeekDays[value]);
        })
    }

I want to get each element of the model and add the value of the days. For example, if i have Monday and Tuesday in model, when performing

console.log(WeekDays[value])

the output is

0
1

And these values i want to add in my array but i get the "Cannot read properties of undefined (reading 'arr')" error.

The array is defined as

arr = Array(7);

What i am doing wrong?

CodePudding user response:

You need to use => to declare your forEach callback.

Functions declared with => capture the value of this from the scope they were created in. function does not. So this is not what you think it is. It's most likely the global object, not your class instance.

Try this instead:

this.model.forEach((value) => {
  this.arr.push(WeekDays[value]);
})
  • Related