TypeScript: Cannot read property 'push' of undefined in [null]

后端 未结 3 1466
别跟我提以往
别跟我提以往 2020-12-28 13:58

Error: Cannot read property \'push\' of undefined in [null].

class A implements OnInit {
    stringArr: string[];

         


        
相关标签:
3条回答
  • 2020-12-28 14:37
    class A implements OnInit {
        stringArr: string=[];
        ngOnInit() {
            for(let i=0; i<4; i++) {
                this.stringArr.push("aaa");
            }
        }
    }
    

    Here stringArr is defined as string, but not as an array of string. Define stringArr as blank array [].

    0 讨论(0)
  • 2020-12-28 14:43

    The array needs to be initialized:

    stringArr = [];
    
    0 讨论(0)
  • 2020-12-28 14:47

    For me the syntax was a little more than the accepted answer because I was using a full array type.

    stringArr: Array<String> = [];
    

    Also, this would work too

    stringArr: String[] = [];
    

    Just 2 ways to type a new array

    0 讨论(0)
提交回复
热议问题