0
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][Instance Methods] forEachメソッドとは (配列→各要素の処理実行), for...ofとforとの違い

Last updated at Posted at 2025-10-27

概要

forEach()Array インスタンスのメソッドで、配列の各要素に対して指定した関数を一度ずつ実行します。
戻り値を返さず、配列を処理することに特化したメソッド です。

つまり、

  • forEach は「配列の各要素に処理を実行する」
    ためのインスタンスメソッドです。

目次

基本構文

JavaScript
// forEach: 各要素に対して処理を実行
const numbers = [1, 2, 3, 4, 5];

numbers.forEach(num => {
  console.log(num * 2);
});

// 出力結果:
// 2
// 4
// 6
// 8
// 10
  • 対象: 配列
  • 戻り値: なし (undefined)
  • 用途: 各要素を使って何らかの処理を実行したいとき(例:表示・加算・削除など)

forEachの特徴

  • コールバック関数が自動的に全要素に対して呼び出される
  • 各反復で「要素・インデックス・元配列」の3情報を受け取れる
  • 戻り値を返さない(新しい配列は作られない)
JavaScript
array.forEach((element, index, array) => {
  // 実行したい処理
});
引数 説明
element 現在処理中の配列の要素
index 現在の要素のインデックス(0, 1, 2, …)
array forEach を呼び出した元の配列

element だけを使うケースが最も多いです。

活用例

1. 各要素を順に出力

JavaScript
const fruits = ["apple", "banana", "cherry"];

fruits.forEach(fruit => {
  console.log(fruit);
});
// 出力結果:
// apple
// banana
// cherry

2. インデックスを利用した処理

JavaScript
const fruits = ["apple", "banana", "cherry"];

fruits.forEach((fruit, index) => {
  console.log(`${index + 1}番目の果物は${fruit}です`);
});
// 出力結果:
// 1番目の果物はappleです
// 2番目の果物はbananaです
// 3番目の果物はcherryです

3. 合計値を計算(配列全体を処理)

JavaScript
const numbers = [1, 2, 3, 4, 5];
let sum = 0;

numbers.forEach(num => {
  sum += num;
});

console.log(sum); // 15

4. 条件付きの処理を行う

JavaScript
const scores = [80, 55, 90, 42, 75];

scores.forEach(score => {
  if (score >= 70) {
    console.log(`${score}点:合格`);
  } else {
    console.log(`${score}点:不合格`);
  }
});
// 出力結果:
// 80点:合格
// 55点:不合格
// 90点:合格
// 42点:不合格
// 75点:合格

5. 配列とUI要素を対応付ける(indexを活用)

JavaScript
const books = [
  { title: "React入門", author: "佐藤" },
  { title: "JS本格入門", author: "田中" },
];

books.forEach((book, index) => {
  const deleteBtn = document.createElement("button");
  deleteBtn.textContent = "削除";
  deleteBtn.addEventListener("click", () => deleteBook(index));

  console.log(`${book.title} の削除ボタンを生成`);
});

index により「UIのボタン」と「データ上の本」を対応づけられます。

for...ofとforとの違い

比較項目 forEach() for...of for
文法タイプ 関数型(宣言的) 命令型 命令型
break/continue
await対応 ❌ 非同期NG
index取得 ✅ 第2引数 ⚠️ 不可 ✅ 直接使用可
用途 各要素への副作用処理 非同期・中断が必要な逐次処理 低レベル・高パフォーマンス
使用頻度(実務) ★★★★★ ★★☆☆☆ ★☆☆☆☆

参考リンク

CodeWars

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