TypeScript:无法读取 [null] 中未定义的属性“push”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35689140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 06:57:09  来源:igfitidea点击:

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

typescript

提问by Ng2-Fun

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

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

class A implements OnInit {
    stringArr: string[];

    ngOnInit() {
        for(let i=0; i<4; i++) {
            this.stringArr.push("aaa");
        }
    }
}

回答by Ng2-Fun

The array needs to be initialized:

数组需要初始化:

stringArr = [];

回答by SeanMC

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

对我来说,语法比接受的答案要多一点,因为我使用的是完整的数组类型。

stringArr: Array<String> = [];

回答by Manish Bhavnani

class A implements OnInit {
    stringArr: string=[];
    ngOnInit() {
        for(let i=0; i<4; i++) {
            this.stringArr.push("aaa");
        }
    }
}

Here stringArris defined as string, but not as an array of string. Define stringArras blank array [].

这里stringArr定义为字符串,而不是字符串数组。定义 stringArr为空数组[]。