In JavaScript, a multi-dimensional array is an array that contains other arrays as elements. This allows you to store data in a grid-like structure, useful for representing things like tables, matrices, or even 3D game worlds.
Here’s how you can create and work with multi-dimensional arrays in JavaScript:
Creating a Multi-dimensional Array
There are two common ways to create a multi-dimensional array:
- Nested Array Literal:
This involves creating an array literal where each element is itself another array literal. Here’s an example:
let chessBoard = [ [1, 2, 3, 4, 5, 6, 7, 8], [8, 7, 6, 5, 4, 3, 2, 1], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [7, 6, 5, 4, 3, 2, 1, 8], [1, 2, 3, 4, 5, 6, 7, 8], ];
This creates a chessboard representation where each element represents a square on the board.
- Nested Arrays with Loops:
You can also use loops to create a multi-dimensional array dynamically. Here’s an example:
let rows = 3; let columns = 4; let table = []; for (let i = 0; i < rows; i++) { table[i] = []; for (let j = 0; j < columns; j++) { table[i][j] = 0; } }
This code creates a 3×4 table filled with zeros.
Accessing Elements
To access elements in a multi-dimensional array, you use nested indexing. The first index accesses the inner array, and the second (and subsequent) index(es) access the elements within that inner array.
For example, in the chessboard example:
console.log(chessBoard[0][1]); // This will output 2 (the knight on the white starting position)
Iterating over a Multi-dimensional Array
You can use nested loops to iterate over the elements of a multi-dimensional array. Here’s an example that prints all the elements of the chessboard:
for (let i = 0; i < chessBoard.length; i++) { for (let j = 0; j < chessBoard[i].length; j++) { console.log(chessBoard[i][j]); } }
Additional Points
- Multi-dimensional arrays can have more than two dimensions (e.g., 3D arrays for games).
- The size of inner arrays can vary, creating ragged multi-dimensional arrays.
By understanding how to create, access, and iterate over multi-dimensional arrays, you can effectively store and manipulate complex data structures in your JavaScript applications.