angular - typescript 以循环方式将元素插入数组

标签 angular typescript

我有一个数组:

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/

相关文章:

javascript - 在 javascript/typescript 中将 Element 转换为 HTMLElement

typescript - 为什么当我将对象显式包装在 `if` 中时,TS 会提示对象可能为空?

angular - 无法解析 [...] 的所有参数

Angular : how to trigger bindings manually?

javascript - 如果对象返回 true,则设置 ngModel

angular - angular 2 中的类型是什么?

typescript - 包装重载的 Typescript 函数

angular - 异步 EventEmitter 的用例

angularjs - Angular 2 嵌套表单组包含空值

css - Angular2 在运行时覆盖 css