1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

JavaScript学習ログ ループ処理のfor文・while文

1
Last updated at Posted at 2025-11-22

ループ処理

同じ処理を繰り返し行う仕組み。
(本日はfor文とwhile文について、学習したことをまとめます。)

ループ処理の種類
・for 文
・do...while 文
・while 文
・ラベルつき文
・break 文
・continue 文
・for...in 文
・for...of 文

for文

回数が決まっているときに使う。

for (初期化式; 条件式; 加算式){
繰り返す処理内容
}

for(let i = 1; i <= 10; i++) {
    console.log(i);
    console.log("お蕎麦");
}

コンソールには数字の1から10が出力される。
また、お蕎麦という文字列が10個出力される。

初期化式で変数を準備し、条件式がtrueの間、処理を繰り返し、1回ごとに加算式が実行される。
falseになったらfor文の繰り返しは終了する。

for(let i = 100; i >= 0; i -= 10 ){
    console.log(i);
}

コンソールには100 90 80 …… 0と表示されます。
加算式の中は加算以外もできます。

◾️配列の中の数だけ繰り返す

const food = ["お蕎麦", "ラーメン", "お寿司"];
for(let i = 0; i < food.length; i++){
    console.log(food[i]);
}

配列は0から始まるため、初期化式はi = 0となります。
food[i] で、配列の各要素を順に取り出して表示します。
コンソールにはお蕎麦 ラーメン お寿司と表示されます。

length は「配列の要素数」を表すプロパティです。
配列の要素数は3ですが、条件式でi <= food.lengthとすると、i[3] (4番目)はundefinedとなります。

while文

条件式がtrueの間繰り返される
条件式がfalseとなる場合、ループ内の文は停止される。

while(条件式){
処理内容。値の更新をしないと無限ループが起こる。
}

let count = 0 ;
while(count < 10){
    count++;
    console.log(count);
}

上記のように繰り返す数が決まっている場合はfor文でも記述可能

let num = 0;
while (num !== 5) {
  num = Math.floor(Math.random() * 10);
  console.log("5が出たので終了");
}

上記のような場合、numが5でない間(true)、ランダムな数を生成する。
数が5になったらランダム生成の繰り返し処理が終わり次の処理に進み、コンソールに5が出たので終了と表示される。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?