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
TypeScript: Cannot read property 'push' of undefined in [null]
提问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 stringArr
is defined as string, but not as an array of string. Define stringArr
as blank array [].
这里stringArr
定义为字符串,而不是字符串数组。定义 stringArr
为空数组[]。