如何在JavaScript和Typescript中实例化多维数组/矩阵,以及如何获得矩阵长度(行数)和矩阵行的长度?
答案 0 :(得分:6)
在Typescript中,您将使用以下语法实例化2x6矩阵/多维数组:
var matrix: number[][] =
[
[ -1, 1, 2, -2, -3, 0 ],
[ 0.1, 0.5, 0, 0, 0, 0 ]
];
//OR
var matrix: Array<number>[] =
[
[ -1, 1, 2, -2, -3, 0 ],
[ 0.1, 0.5, 0, 0, 0, 0 ]
];
JavaScript中的等价物是:
var matrix =
[
[ -1, 1, 2, -2, -3, 0 ],
[ 0.1, 0.5, 0, 0, 0, 0 ]
];
JavaScript语法在TypeScript中也有效,因为类型是可选的,但TypeScript语法在JavaScript中无效。
要获得不同的长度,您将在JS和TS中使用相同的语法:
var matrixLength = matrix.length; // There are two dimensions, so the length is 2. This is also the column size.
var firstDimensionLength = matrix[0].length; // The first dimension row has 6 elements, so the length is 6
var secondDimensionLength = matrix[1].length; // The second dimension row has 6 elements so the length is 6