如何在 TypeScript 中初始化(声明)一个数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43637230/
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
How to initialize (declare) an array in TypeScript?
提问by Sohrab
I am absolute beginner on TypeScript. I want to initialize an array of numbers in TypeScript by "for" loop as you see in the following:
我绝对是 TypeScript 的初学者。我想通过“for”循环在 TypeScript 中初始化一个数字数组,如下所示:
public hours: number[];
constructor() {
for (let i: number = 1; i < 25; i++) {
this.hours[i] = i;
}
}
I get an error: Cannot set property '1' of undefined. Could you please help me?
我收到一个错误:无法设置未定义的属性“1”。请你帮助我好吗?
回答by Nitzan Tomer
This line:
这一行:
public hours: number[];
Does not create a new array, it only declares it.
If you compile this code:
不创建新数组,它只声明它。
如果编译此代码:
class MyClass {
public hours: number[];
constructor() {
for (let i: number = 1; i < 25; i++) {
this.hours[i] = i;
}
}
}
You get:
你得到:
var MyClass = (function () {
function MyClass() {
for (var i = 1; i < 25; i++) {
this.hours[i] = i;
}
}
return MyClass;
}());
As you can see, this.hours
isn't being assigned.
如您所见,this.hours
没有被分配。
So you need to do this:
所以你需要这样做:
constructor() {
this.hours = [];
for (let i: number = 1; i < 25; i++) {
this.hours[i] = i;
}
}
Or:
或者:
public hours: number[] = [];
回答by JusMalcolm
hours isn't set to any value. You can create a new array in the constructor, or set hours to an empty array:
小时未设置为任何值。您可以在构造函数中创建一个新数组,或将 hours 设置为空数组:
public hours: number[] = [];
constructor() {
for (let i: number = 1; i < 25; i++) {
this.hours[i] = i;
}
}