在嵌套for循环的条件下改变变量



我试图用嵌套的for循环打印出所有天的所有乐队,但我坚持如何在第一个循环中改变第二个循环的日期。是否有一种方法可以从数组中读取日期并使用它们?

我得到这个错误

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);

你写的是midgard。whatDay[x],因为whatDay不是midgard的属性,所以没有定义,你无法访问它。试着用这一行替换它:

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

你可能也应该改变下一行:

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

我想这就是你的问题:

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);

相关内容

  • 没有找到相关文章

最新更新