首页 > 解决方案 > 以角度创建具有日期和星期的数组数组

问题描述

我正在尝试创建一个数组数组,每周将日期重新组合为 7 7。就像是

full_dates = [
[{date: 'Mon 12', date: 'Tue 13, date: 'Wed 14'}],
[{date: 'Mon 19', date: 'Tue 20, date: 'Wed 21'}],
and so on
];

所以我开始它所做的就是创建一个包含我需要的所有日期的数组,给出一个开始和停止。

然后,我想循环这个值,每次循环中 i%7 等于 0,我改变周并尝试将它保存在我的“大数组”中的另一个数组中。

所以我做了类似的事情。

// initialize full_calendar
full_calendar: any[] = [[]];

...

// create an array of date between an initial date and a final date
let initialTime = new Date("2020-10-12Z08:00:00");
let endTime     = new Date("2020-10-27Z08:00:00");

for (let q = initialTime; q <= endTime; q.setDate(q.getDate() + 1)) {
  this.dates.push(q.toString());
}
console.log(this.dates);

// make a loop for each date, and regroup them by 7 for a week 
let week = -1;
for (let i = 0; i<14;i++) {
  if (i%7 == 0) {
    week += 1;
  }
this.full_calendar[week].push({date:this.dates[i]});

}
console.log(this.full_calendar);

但我收到错误:TypeError:无法读取未定义的属性“推送”类型错误:无法读取未定义的属性“推送”

看起来,好像我无法在数组中创建新数组。也许我应该再做一次初始化?

谢谢

标签: angularionic-framework

解决方案


您需要对代码进行小的更改

full_calendar: any[][] = [];

...

let week = 0; // Week needs to start from 0
for (let i = 0; i < 14; i++) { // Instead of 14, it might be difference between start and end date
  if (i % 7 == 0 && i !== 0) {
    week += 1;
  }
  // As you initialized `full_calendar` as an empty array, you need to do undefined check
  if (this.full_calendar[week]) {
    this.full_calendar[week].push({
      date: this.dates[i]
    });
  } else {
    this.full_calendar[week] = [{
      date: this.dates[i]
    }];
  }
}

推荐阅读