angular - 以角度创建具有日期和星期的数组数组
问题描述
我正在尝试创建一个数组数组,每周将日期重新组合为 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:无法读取未定义的属性“推送”类型错误:无法读取未定义的属性“推送”
看起来,好像我无法在数组中创建新数组。也许我应该再做一次初始化?
谢谢
解决方案
您需要对代码进行小的更改
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]
}];
}
}
推荐阅读
- oracle - 在 WebLogic 10.3.6.0 上部署错误消息
- php - 如何使用 PHP ldap_modify 更新 Active Directory 中的照片
- react-native - 异步存储错误未处理的承诺拒绝在交换机
- sql-server - 具有不同列数的存储过程 INSERT INTO
- javascript - 如何强制检查表单的复选框?
- python - 从一种形式创建模型实例两次
- xcode - Uitextfield背景颜色模糊?
- android - 如何创建在单击按钮时将语音更改为文本语言的 android 应用程序
- mongodb - 具有多个条件和 id 的 mongodb 聚合查找
- python - 在 Python 3 中处理多个输入变量