22
10

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のループ構文まとめ

Posted at

JavaScriptのループ構文まとめ【for, while, for...of, for...in】

📝 目次

  1. ループとは?
  2. JavaScriptの主なループ構文
  3. for文の基本構文と例
  4. 無限ループに注意
  5. 配列をループで処理する
  6. ループのネスト(二重ループ)
  7. while文の使い方
  8. breakでループを抜ける
  9. for...of文の使い方
  10. まとめ

ループとは?

  • ループは、同じ処理を繰り返し実行したい時に使います。
    • 例:「'hello'を10回出力する」「配列内の全要素の合計を求める」など
  • さまざまな書き方が用意されているので、目的に応じて使い分けましょう。

JavaScriptの主なループ構文

  • for
  • while
  • for...of
  • for...in

それぞれ得意な用途が異なります。


for文の基本構文と例

基本構文

for ([初期化式]; [条件式]; [増減式]) {
  // 繰り返す処理
}

例:1から10まで出力

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

無限ループに注意

⚠️ 条件を間違えると無限ループになるので注意!

// for (let i = 20; i >= 0; i++) {
//   console.log(i);
// }

配列をループで処理する

配列の全要素を順番に出力

const languages = [
  'JavaScript',
  'Python', 
  'Java',      
  'C#',       
  'Go',   
  'Ruby',        
  'PHP'
  'Swift',      
  'Kotlin',      
  'TypeScript',  
  'C++',        
  'Rust',       
  'Scala',     
  'Perl',  
  'R',           
  'Dart',    
  'Shell',   
  'Elixir',      
  'Haskell',    
  'Objective-C', 
];

// 先頭から順に
for (let i = 0; i < languages.length; i++) {
  console.log(i, languages[i]);
}

// 末尾から順に
for (let i = languages.length - 1; i >= 0; i--) {
  console.log(i, languages[i]);
}


ループのネスト(二重ループ)

2次元配列(配列の配列)をすべて出力したいときは、**ループを入れ子(ネスト)**にします。

const cityGroups = [
  ['東京', '大阪', '名古屋'],
  ['ニューヨーク', 'ロサンゼルス', 'シカゴ', 'ヒューストン'],
  ['ロンドン', 'マンチェスター', 'バーミンガム'],
];

for (let i = 0; i < cityGroups.length; i++) {
  let country = cityGroups[i];
  for (let j = 0; j < country.length; j++) {
    console.log(country[j]);
  }
}

while文の使い方

while文は、条件がtrueの間だけ繰り返します。

let count = 0;

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

breakでループを抜ける

break文を使うと、途中でループを強制終了できます。

let input = prompt('何か入力してください');

while (true) {
  input = prompt(input);
  if (input === 'quit') break;
}

for...of文の使い方

for...ofは、配列など列挙可能なオブジェクトの各要素を順番に処理できます。

const youtubeCategories = [
  'music',
  'gaming',
  'education',
  'vlogs',
  'tech',
  'travel',
  'comedy',
];

for (let category of youtubeCategories) {
  console.log(`Check videos in the "${category}" category on YouTube!`);
}

// ちなみに従来のfor文でも同じ結果
// for (let i = 0; i < youtubeCategories.length; i++) {
//   console.log(`Check videos in the "${youtubeCategories[i]}" category on YouTube!`);
// }

まとめ

  • ループ構文を使うと、同じ処理を効率よく繰り返せる
  • forwhileは「回数指定」や「条件指定」の繰り返しに強い
  • for...ofは配列処理がシンプルに書ける
  • 無限ループや条件ミスには注意!
22
10
1

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
22
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?