angular2 和 Typescript 数组 - 类型“() => void”上不存在属性“push”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38832634/
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
angular2 and Typescript array - Property 'push' does not exist on type '() => void'
提问by Tampa
How do I init an empty array?
如何初始化一个空数组?
test: any[];
//On change I want to add an item to an array
test(){
this.test.push('a');
}
error TS2339: Property 'push' does not exist on type '() => void'.
错误 TS2339:类型“() => void”上不存在属性“push”。
回答by Thierry Templier
You don't initialize your array, so test
is undefined
. To be able to use it, just initialize it this way:
你没有初始化你的数组,所以test
是undefined
. 为了能够使用它,只需以这种方式初始化它:
test: any[] = [];
回答by Harrison O
Try any of these solutions:
尝试以下任何一种解决方案:
const test = [];
test.push('a');
OR
或者
const test = [];
const name = 'a';
test.push({ 'name' : name});
You can add it to your function like:
您可以将其添加到您的函数中,例如:
test(name: string){
const test = [];
test.push({ 'name' : name});
}