我有一个数组:
public roundRobinMonths: any=['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
和另一个空数组:public userTimeline: any=[];
我的用户将从日期选择器中选择一个月,如果他选择说九月,那么我想在我的userTimeline数组中添加从10月到9月的月份,即10月,11月,...,Apl,Mai,..., 8月,9月
我在组件索引中收到用户选择的月份,即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;
}
});
}
这只会增加一个月。什么是正确的逻辑?
答案 0 :(得分:2)
您可以尝试slice
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);
});
}
答案 1 :(得分:1)
// store the selected month as an index
const selectedMonth = this.selectedDate.month();
// get all months after the selected one
// (we get all between the selected one and the end)
const monthsAfterSelected
= this.roundRobinMonths.slice(selectedMonth + 1, this.roundRobinMonths.length);
// get all months before the selected one
// (we get all from index 0 to the selected one)
const monthsBeforeSelected = this.roundRobinMonths.slice(0, selectedMonth + 1);
// this is the months in round robin order - place the arrays together
const orderedMonths = monthsAfterSelected.concat(monthsBeforeSelected);
// push them all into the user timeline
orderedMonths.forEach(m => {
this.userTimeline.push(m);
});
以下是JavaScript中函数的快速示例:
function getRoundRobin(index) {
const months = ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'July', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
const after = months.slice(index + 1, months.length);
const before = months.slice(0, index + 1);
return after.concat(before);
}
console.log(getRoundRobin(8)); // select September