LoginSignup
1
2

More than 3 years have passed since last update.

JavaScript (配列)

Last updated at Posted at 2019-10-07

配列とは

複数の値をまとめて管理するときに用いる。
[値1,値2,値3]のように使う。
配列に入っているそれぞれの値のことを「要素」と呼ぶ。

//文字列をまとめた配列
["apple","banana","orange"]
//数値をまとめた配列
[21,52,14]

配列を定数に代入する

配列を代入する定数名は、複数形にすることが多い。

//書き方
const fruits = ["apple","banana","orange"];
console.log(fruits);
//コンソール
["apple","banana","orange"]

配列の要素を取得する

インデックス番号

要素についている番号。
0から始まる。
配列 [インデックス番号]で、その番号の要素を取得できる。

//書き方
const fruits = ["apple","banana","orange"];
console.log(fruits[0]);
console.log(fruits[2]);
//コンソール
apple
orange

配列の要素を更新する

要素は上書きすることが可能。

//書き方
const fruits = ["apple","banana","orange"];
console.log(fruits[0]);
fruits[0]="grape";
console.log(fruits[0]);
//コンソール
apple
grape

配列とfor文

通常、要素をすべて出力するときは↓

const fruits = ["apple","banana","orange"];
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

要素数が増えると、全部書くの大変:sweat:

for文を使う↓

//・**変数 i**を用いる。
//・iが0~2(インデックス番号)の間ループする。
const fruits = ["apple","banana","orange"];
for(let i = 0;i < 3;i++){
console.log(fruits[i]);
}

とすることで、変数数が100になっても簡単に書くことができる。

length

配列の要素数を取得できる。
(要素の数が分かる。)

//書き方
const fruits = ["apple","banana","orange"];
console.log(fruits.length);
//コンソール
3

配列でよく使います↓

const fruits = ["apple","banana","orange"];

console.log(fruits.length);

for(let i = 0;i < fruits.length;i++){
console.log(fruits[i]);
}
//コンソール
3
apple
banana
orange
1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2