Faris Zacina
Faris Zacina

Reputation: 14274

How to instantiate and get a length of a multidimensional array / matrix?

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?

Upvotes: 5

Views: 10723

Answers (1)

Faris Zacina
Faris Zacina

Reputation: 14274

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

Upvotes: 8

Related Questions