类型脚本-多维数组初始化

我正在玩 Typecript,我想知道如何正确地实例化和声明多维数组:

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 ???
}
}
}
}

你能给我一些关于选定地点的提示吗?

188842 次浏览

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.

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();
}
}
}
}

If you want to do it typed:

class Something {


areas: Area[][];


constructor() {
this.areas = new Array<Array<Area>>();
for (let y = 0; y <= 100; y++) {
let row:Area[]  = new Array<Area>();
for (let x = 0; x <=100; x++){
row.push(new Area(x, y));
}
this.areas.push(row);
}
}
}

Beware of the use of push method, if you don't use indexes, it won't work!

var main2dArray: Things[][] = []


main2dArray.push(someTmp1dArray)
main2dArray.push(someOtherTmp1dArray)

gives only a 1 line array!

use

main2dArray[0] = someTmp1dArray
main2dArray[1] = someOtherTmp1dArray

to get your 2d array working!!!

Other beware! foreach doesn't seem to work with 2d arrays!

Here is an example of initializing a boolean[][]:

const n = 8; // or some dynamic value
const palindrome: boolean[][] = new Array(n)
.fill(false)
.map(() =>
new Array(n).fill(false)
);

You can do the following (which I find trivial, but its actually correct). For anyone trying to find how to initialize a two-dimensional array in TypeScript (like myself).

Let's assume that you want to initialize a two-dimensional array, of any type. You can do the following

const myArray: any[][] = [];

And later, when you want to populate it, you can do the following:

myArray.push([<your value goes here>]);

A short example of the above can be the following:

const myArray: string[][] = [];
myArray.push(["value1", "value2"]);