打字稿以循环方式将元素推入数组 [英] typescript push elements into an array in roundrobin fashion
本文介绍了打字稿以循环方式将元素推入数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数组:
public roundRobinMonths: any=['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
和另一个空数组: public userTimeline:any = [];
我的用户将从日期选择器中选择一个月,如果他选择说9月,那么我想在我的userTimeline数组中添加从10月到9月的月份,即Oct,Nov,...,Apl,Mai,...,八月,九月
My user will select a month from a datepicker and if he selects say September then I want to add months starting from Oct until Sep in my userTimeline array i.e. Oct, Nov,..., Apl, Mai,..., Aug, Sep
我在组件索引中收到一个月,用户选择了0、1,..,11.
I receive in my component index for a month that user selects i.e. 0, 1,.., 11.
我尝试运行如下所示的for循环:
I tried running a for loop like following:
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;
}
});
}
这仅增加一个月.正确的逻辑是什么?
This adds only one month. What could be the correct logic?
推荐答案
您可以尝试切片
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);
});
}
这篇关于打字稿以循环方式将元素推入数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文