Home > Mobile >  chaning variables in the condition of a nested for loop
chaning variables in the condition of a nested for loop

Time:12-11

I am trying to print out all bands for all days with a nested for-loop but im stuck with how to change the day in the second loop with the first loop. Is there a way to read the days from the array and use them?

i get this error

TypeError: Cannot read properties of undefined (reading '0')
const whatDay = ["mon", "tue", "wed"];

function playingWhen(whatDay) {
  for (let x = 0; x < whatDay.length; x  ) {
    for (let i = 0; i < midgard.whatDay[x].length; i  ) {
      console.log(i, midgard.mon[i].act);
    }
  }
}

playingWhen(whatDay);

const midgard = {
  mon: [
    { start: "00:00", end: "02:00", act: "Barrows Group", cancelled: true },
    { start: "02:00", end: "04:00", act: "break" },
  ],
  tue: [
    { start: "00:00", end: "02:00", act: "Bartell - Cummerata", cancelled: true },
    { start: "02:00", end: "04:00", act: "break" },
  ],
  wed: [
    { start: "00:00", end: "02:00", act: "A Perfect Circle" },
    { start: "02:00", end: "04:00", act: "break" },
  ],
};

playingWhen(whatDay);

CodePudding user response:

you wrote midgard.whatDay[x], since whatDay is not a property of midgard, it is undefined, and you can't access it. try replacing it with this line:

for (let i = 0; i < midgard[whatDay[x]].length; i  )

You probably should change the next line too:

console.log(i, midgard[whatDay[x]][i].act);

CodePudding user response:

I think this is what you want in your question:

const midgard = {
  mon: [
    { start: "00:00", end: "02:00", act: "Barrows Group", cancelled: true },
    { start: "02:00", end: "04:00", act: "break" },
  ],
  tue: [
    { start: "00:00", end: "02:00", act: "Bartell - Cummerata", cancelled: true },
    { start: "02:00", end: "04:00", act: "break" },
  ],
  wed: [
    { start: "00:00", end: "02:00", act: "A Perfect Circle" },
    { start: "02:00", end: "04:00", act: "break" },
  ],
};

const whatDay = ["mon", "tue", "wed"];

function playingWhen(whatDay) {
  for (let x = 0; x < whatDay.length; x  ) {
    console.log('Day: '   whatDay[x]);
    for (let i = 0; i < midgard[whatDay[x]].length; i  ) {
      let currentBand = midgard[whatDay[x]][i];
      console.log(i, currentBand.act);
    }
  }
}

playingWhen(whatDay);

  • Related