无法读取未定义的属性"push"? [英] Cannot read property 'push' of undefined?

查看:113
本文介绍了无法读取未定义的属性"push"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下简单代码:

  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??为什么我有正确的数据类型作为数组?

It gives me an error: Cannot read property 'push' of undefined?? Why if I have correct data type as array?

推荐答案

您必须将年份初始化为空数组,否则为null

You have to initialize years to empty array, otherwise it is null

 private years: number[] = [];

这篇关于无法读取未定义的属性"push"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆