我有一个数组:
public roundRobinMonths: any=['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
和另一个空数组:public userTimeline: any=[];
我的用户将从日期选择器中选择一个月,如果他选择九月,那么我想在我的 userTimeline 数组中添加从十月到九月的月份,即十月,十一月,...,四月,五月,...,八月、九月
我在组件索引中收到用户选择的一个月,即 0、1、..、11。
我尝试运行如下 for 循环:
public pickDate($event: MouseEvent) {
this.datePicker.selectDate(this.selectedWeddingDate, {openFrom: $event}).subscribe( (selectedDate: Date) => {
this.selecteDate = selectedDate ? moment(selectedDate) : null;
// logic for creating personalized timeline
switch (this.selectedDate.month()) {
case 8:
for(let month of this.roundRobinMonths){
if(this.roundRobinMonths.indexOf(month)===8){
this.userTimeline.push(month)
console.log(this.userTimeline)
}
}
break;
default:
// code...
break;
}
});
}
这仅增加了一个月。正确的逻辑是什么?
最佳答案
您可以尝试切片
public pickDate($event: MouseEvent) {
this.datePicker.selectDate(this.selectedWeddingDate, { openFrom: $event }).subscribe((selectedDate: Date) => {
this.selecteDate = selectedDate ? moment(selectedDate) : null;
// logic for creating personalized timeline
let month = this.selectDate.month() + 1;
this.userTimeline = this.roundRobinMonths.slice(month , 12).concat(this.roundRobinMonths.slice(0 , month));
console.log(this.userTimeline);
});
}
关于angular - typescript 以循环方式将元素插入数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46442789/