JavaScript における 配列(Array) は、複数の値を 1 つの変数にまとめて管理できるデータ構造 です。
たとえば「りんご・バナナ・みかん」のように、関連するデータをまとめて扱いたいときに便利です。
順序を持ったデータの集まりです。先頭はインデックス 0 から始まります。
異なる型のデータ(数値・文字列・オブジェクト・関数 など)を混ぜて入れることができます。
配列の中に配列を入れる「多次元配列」のような使い方もできます。
const fruits = ["apple", "banana", "orange"]; fruits[0] → "apple" fruits[1] → "banana" fruits[2] → "orange"
const 配列名 = [値1, 値2, 値3];
const fruits = ["apple", "banana", "orange"]; const numbers = [1, 2, 3, 4, 5]; const mixed = [true, 123, "hello", { name: "Taro" }];
コピペではなく実際に打ち込んで練習してみましょう。
const fruits = ["apple", "banana", "orange"]; console.log(fruits[0]); // "apple" console.log(fruits[2]); // "orange"
const fruits = ["apple", "banana", "orange"]; console.log(fruits.length); // 3
const fruits = ["apple", "banana", "orange"]; fruits.push("grape"); console.log(fruits); // ["apple", "banana", "orange", "grape"]
const fruits = ["apple", "banana", "orange"]; fruits.pop(); console.log(fruits); // ["apple", "banana", "orange"]
const fruits = ["apple", "banana", "orange"]; fruits.unshift("melon"); console.log(fruits); // ["melon", "apple", "banana", "orange"]
const fruits = ["apple", "banana", "orange"]; fruits.shift(); console.log(fruits); // ["apple", "banana", "orange"]
const fruits = ["apple", "banana", "orange"]; const newFruits = fruits.slice(1, 3); console.log(newFruits); // ["banana", "orange"]
const fruits = ["apple", "banana", "orange"]; fruits.forEach(fruit => { console.log(fruit); }); // apple // banana // orange