Comp 110 2D Arrays: Creating a 2D array

Creating a 2D array

2D array is just an "array of arrays." We can essentially think of this as being a 2D grid, with each element in the grid being of the same type. The general syntax for declaring a 2D array is:

let <name>: <type>[][]; // example usage:
let dictionary: string[][];

When creating a 2D array we also need to consider how we will be accessing elements. A column-major 2D array means that the columns array is the outer most array. Similarly, row-major means that the rows array is the outer array. In this class, you can assume all 2D arrays you are working with are row-major. For example, if you wanted to access the 3rd item in the 1st row, you would do:

let x = randomArray[1][3];

We use the index of the row first and then the index of the column. Keep in mind that when we are working with arrays, the indices are off by one since we start at 0. So in this case, the element at randomArray[1][3] is actually in the second row & fourth column when looking at the grid visually.