LoginSignup
0
0

More than 1 year has passed since last update.

配列を操作するforEachとmapの違い

Posted at

はじめに

Javascriptの配列操作を学んだ際、forEachとmapの違いがいまいちピンとこなかったので当時の自分に書くつもりで完結にまとめてみました。

forEachの使い方

forEachは配列の値を順番に一つずつ取り出して設定した処理を実行します。
下記だと配列に格納された数字を一つずつ取り出して2倍して出力します。

const array = [1, 2, 3, 4, 5];

array.forEach(el => {
  console.log(el * 2);
});

//出力:2 4 6 8 10

mapの使い方

それに対してmapは、配列の値を順番に一つずつ取り出して設定した処理を実行するというところまで同じです。しかし、それに加えて処理の結果を配列として生成しなおすという性質を持っています。

そのため、mapは下記のように配列に処理を加えて新たに生成した配列を出力します。

const array = [1, 2, 3, 4, 5];

const newArray = array.map(el => {
   return el * 2;
});

console.log(newArray);

//出力 [2, 4, 6, 8, 10]

ただ値を出力するだけならforEach

mapでもできてしまいますがmapは新たな配列を生成するという意味合いが強いのでわざわざ使う意味はないでしょう。この場合はforEachが適切です。

const array = [1, 2, 3, 4, 5];

//適切
array.forEach(el => {
  console.log(el * 2);
});

//わざわざこう書く意味はない
array.map(el => {
  console.log(el * 2);
});

//どちらも出力は:2 4 6 8 10

配列の生成はmapしかできない

逆に新たな配列を生成した時、forEachは使えません。この時はmapが適切です。

const array = [1, 2, 3, 4, 5];

//適切
const newArray = array.map(el => {
   return el * 2;
});

console.log(newArray);
//出力 [2, 4, 6, 8, 10]

//-----------------------------------------

//値が返ってこず出力はundefinedになる。
const newArray = array.map(el => {
   return el * 2;
});

console.log(newArray);
//出力 undefined

まとめ

最近は文字列や数字の配列を弄る機会が多いのでmapばかり使っていますが、取得した値を出力したりpushで空の配列に格納したりする場合はforEachが便利ですね。

配列の処理は他にもいろんな特性やメソッドがあるのでMDNなどで調べながら使っていきます。

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