-2

I have a problem that I want to go through an array with a for loop, but for some reason the loop doesn't go through it and just prints the first element of the array everywhere.

Here is my array with the days:

readonly days: WeekDayName[] = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; 

And my functions is what it looks like now:

get dayName() {
  for (const { item, index } of this.days.map((item, index) => ({ item, index }))) {
    return (item);
  }
} 

How can I solve not just print the first item everywhere?

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
vargaadam
  • 411
  • 5
  • 18

3 Answers3

1

Return statement gets you out of the loop. If you want to use an item that is iterated over in the for loop just store in a global variable. and use break statement to fall out of the loop Also important to notice that returns take you out of nested loops as well

Check this detailed answer on return vs break

hassan ahmed
  • 593
  • 3
  • 13
1

Getter functions can't return the iteration values. You just can get an element in result of getters.

Ali Torki
  • 1,929
  • 16
  • 26
0

You are returning the item after one iteration. What you should do is to create an empty array/map and on each iteration you can add the item to it. Then return that array.

Khalil
  • 410
  • 5
  • 13