配列とは

複数のデータを一つの変数でまとめて管理するための仕組みです。各データには 0 から始まるインデックス番号でアクセスします。

配列の宣言と初期化

// 空の配列
const emptyArray = [];

// 値を持つ配列
const scores = [80, 90, 75];

// コンソールで確認
console.log(scores);

要素へのアクセスと更新

const colors = ['red', 'blue', 'green'];

// 値の取得(インデックスは0から)
console.log(colors[0]); // "red"

// 値の変更
colors[1] = 'yellow';
console.log(colors); // ["red", "yellow", "green"]

配列の基本メソッド

const fruits = ['apple', 'banana'];

fruits.push('orange'); // ['apple', 'banana', 'orange']
const last = fruits.pop(); // last: 'orange', fruits: ['apple', 'banana']
console.log(fruits.length); // 2

多次元配列

配列の要素にさらに配列を入れることで、表形式のようなデータを扱うことができます。

const matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];
console.log(matrix[1][2]); // 6 (2行目の3列目)