Typescript - 多维数组初始化 [英] Typescript - multidimensional array initialization
问题描述
我正在使用 Typescript,我想知道如何正确实例化和声明多维数组.这是我的代码:
I'm playing with Typescript and I wonder, how to properly instantiate and declare multidimensional array. Here's my code:
class Something {
private things: Thing[][];
constructor() {
things = [][]; ??? how instantiate object ???
for(var i: number = 0; i < 10; i++) {
this.things[i] = new Thing[]; ??? how instantiate 1st level ???
for(var j: number = 0; j< 10; j++) {
this.things[i][j] = new Thing(); ??? how instantiate 2nd lvl item ???
}
}
}
}
你能给我一些关于选定地点的提示吗?
Can you give me any hint about selected places?
推荐答案
您只需要 []
来实例化一个数组 - 无论其类型如何,这都是正确的.数组是数组类型这一事实并不重要.
You only need []
to instantiate an array - this is true regardless of its type. The fact that the array is of an array type is immaterial.
同样的事情适用于循环的第一级.它只是一个数组,而 []
是一个新的空数组 - 工作完成.
The same thing applies at the first level in your loop. It is merely an array and []
is a new empty array - job done.
至于第二层,如果 Thing
是一个类,那么 new Thing()
就可以了.否则,根据类型,您可能需要一个工厂函数或其他表达式来创建一个.
As for the second level, if Thing
is a class then new Thing()
will be just fine. Otherwise, depending on the type, you may need a factory function or other expression to create one.
class Something {
private things: Thing[][];
constructor() {
this.things = [];
for(var i: number = 0; i < 10; i++) {
this.things[i] = [];
for(var j: number = 0; j< 10; j++) {
this.things[i][j] = new Thing();
}
}
}
}
这篇关于Typescript - 多维数组初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!