无法读取属性'推送'未定义?

时间:2017-08-17 11:40:40

标签: angular

我有以下简单的代码:

  export class Years {

      private years: number[];
      private currentYear: number;

      constructor() {
        this.currentYear = new Date().getFullYear();
        this.years.push(this.currentYear + 1);
        for (let i = this.currentYear; i < this.currentYear - 5; i--) {
          this.years.push(i);
        }
      }
}

它给了我一个错误:Cannot read property 'push' of undefined??为什么我的数据类型正确为数组?

1 个答案:

答案 0 :(得分:6)

您必须初始化年​​份以清空数组,否则它为空

 private years: number[] = [];