How do i instantiate a multidimensional array / matrix in JavaScript and Typescript, and how do i get the matrix length (number of rows) and lengths of the matrix rows?
To get the length of a multidimensional (row/column) array, we can use the Array. GetLength() method in C#. Let's say you have a multidimensional array like this. Note: Dimensions are zero-based (0) indexing.
Size of a matrix = number of rows × number of columns. It can be read as the size of a matrix and is equal to number of rows “by” number of columns.
We use arrayname. length to determine the number of rows in a 2D array because the length of a 2D array is equal to the number of rows it has. The number of columns may vary row to row, which is why the number of rows is used as the length of the 2D array.
In Typescript you would instantiate a 2x6 Matrix / Multidimensional array using this syntax:
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 ]
];
The equivalent in JavaScript would be:
var matrix =
[
[ -1, 1, 2, -2, -3, 0 ],
[ 0.1, 0.5, 0, 0, 0, 0 ]
];
The JavaScript syntax is also valid in TypeScript, since the types are optional, but the TypeScript syntax is not valid in JavaScript.
To get different lengths you would use the same syntax in JS and 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With