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】forEach()とmap()の違い

Posted at

forEach()

forEach()メソッドは、配列の各要素に対して指定された関数を一度ずつ実行します。ログ出力や要素の直接変更などの操作に適しています。

構文

array.forEach(callback(currentValue, index, array), thisArg);

const numbers = [1, 2, 3, 4];

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

// 出力:
// 2
// 4
// 6
// 8

map()

map()メソッドは、配列の各要素に指定された関数を適用し、その結果から新しい配列を作成します。データの変換や加工によく使用されます。

構文

map((currentElement, indexOfElement, array) => { ... });

const numbers = [1, 2, 3, 4];

const doubledNumbers = numbers.map((number) => {
  return number * 2;
});

console.log(doubledNumbers);
// [2, 4, 6, 8]

主な違い

項目 forEach() map()
戻り値 undefined 新しい配列
用途 副作用を伴う処理 データの変換
メソッドチェーン 不可 可能(reduce(), sort()など)

どちらを使うべきか

  • forEach()を使う場合: 配列を単に繰り返し処理したい場合や、変換を必要としない処理(コンソール出力、DOM操作など)
  • map()を使う場合: 配列の各要素を変換して新しい配列を作成したい場合や、後続のメソッドをチェーンしたい場合

参考

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?