0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

配列と繰り返し処理

Last updated at Posted at 2021-04-27

#概要
配列についての復習と配列の取り出し方。
for文での配列の繰り返し処理について。

#配列について
データが順番に並んだ1つのデータを指します。
例えば、以下のようにフルーツデータがあるとします。

index.js
 const fruits1 = "りんご";
 const fruits2 = "バナナ";
 const fruits3 = "ぶどう";
 const fruits4 = "なし";
 const fruits5 = "みかん";

データが膨大で、管理するのに苦労します。
そこで、同じ意味合いのデータとして管理していきます。
以下になります。

index.js
const fruits = ["りんご","バナナ","ぶどう","なし"];

定数フルーツにりんごなどの要素が配列として格納されています。
コンソールで確認すると以下のような結果になります。

スクリーンショット 2021-04-28 12.57.28.png

配列は0番始まりになります。
lengthは要素の数を表すプロパティになります。

#for文使わない場合
配列の要素を取り出す際には以下のようになります。

index.js
console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
console.log(fruits[3]);
console.log(fruits[4]);

スクリーンショット 2021-04-28 13.02.16.png
要素をとりだすことができました。

しかし、要素数が増えたときにコード量が膨大になってしまいます。
そこで、ループ処理を使って行きます。

#for文

index.js
    for (let i = 0;i <= fruits.length;i++) {
      console.log(fruits);
    }

スクリーンショット 2021-04-28 13.35.47.png

index.js
    for (let i = 0;i <= fruits.length;i++) {
      console.log(`フルーツ${i}: ${fruits[i]}`);
    }

スクリーンショット 2021-04-28 6.48.56.png

変数は0~始まります。上記のコードは実質6つ取り出すことになっています。
undifeunedは要素がありませんという意味です。

よってコードを、以下のように変更しました。

index.js
    for (let i = 0;i < fruits.length;i++) {
      console.log(`フルーツ${i}:${fruits[i]}`)
    }

iは要素数5未満。つまり0~4の繰り返しになります。
よって要素数とiの変数が合致したことになります。

スクリーンショット 2021-04-28 13.54.25.png

#forEach

forEachを使用するとコードが更にわかりやすくなります。

index.js
    fruits.forEach((fruit,index) => {
      console.log(`フルーツ${index}:${fruit}`)
    });

引数は自由に決めることができます。
配列の要素を1つずつ受け取って、要素数がなくなるまで繰り返し処理を実行してくれます。
このforEachを使うことで、配列要素が増えたとしてもforEach内を修正することなく使うことができます!

0
1
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
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?