Arrays and 2D Arrays
Arrays let you store multiple values in a single variable - like a row of boxes where each box holds a value.
What is an Array?
An array is a collection of values. In JavaScript, we create arrays using square brackets:
let fruits = ["apple", "banana", "orange", "grape", "kiwi"];
Accessing Array Elements
Each element has a position called an index, starting at 0. To access an element, use its index:
let fruits = ["apple", "banana", "orange"];
let firstFruit = fruits[0]; // "apple"
let secondFruit = fruits[1]; // "banana"
Modifying Arrays
You can change array values or find out how many items are in an array:
let numbers = [10, 20, 30, 40, 50];
numbers[2] = 35; // Changes third element to 35
console.log(numbers.length); // 5
2D Arrays (Grids)
A 2D array is an array of arrays - like a grid with rows and columns.
Creating a 2D array:
let grid = [
[1, 2, 3], // Row 0
[4, 5, 6], // Row 1
[7, 8, 9] // Row 2
];
Accessing Grid Elements
To access elements in a 2D array, we need two indices: row and column.
let value = grid[1][2]; // Row 1, Column 2: value 6
Arrays in Conway's Game of Life
In our Game of Life simulation, we use a 2D array to represent the grid:
- Each cell can be 0 (dead) or 1 (alive)
- We need to loop through all cells to apply the rules
Creating the Game Grid
// Calculate grid dimensions
cols = Math.floor(width / resolution);
rows = Math.floor(height / resolution);
// Create and initialize the grid
grid = new Array(cols);
for (let i = 0; i < cols; i++) {
grid[i] = new Array(rows);
for (let j = 0; j < rows; j++) {
grid[i][j] = 0; // All cells start dead
}
}
Looping Through the Grid
To apply rules to each cell, we use nested loops:
// Loop through every cell
for (let i = 0; i < cols; i++) {
for (let j = 0; j < rows; j++) {
// Do something with grid[i][j]
}
}
Finding Neighbors
In Conway's Game of Life, we need to check the 8 surrounding cells:
// Count neighbors around cell at (x,y)
function countNeighbors(grid, x, y) {
let sum = 0;
for (let i = -1; i <= 1; i++) {
for (let j = -1; j <= 1; j++) {
// Skip the cell itself
if (i === 0 && j === 0) continue;
// Handle edge wrapping
let col = (x + i + cols) % cols;
let row = (y + j + rows) % rows;
sum += grid[col][row];
}
}
return sum;
}
Practice: Count Live Neighbors
Complete the function to count the number of live neighbors for a cell: