JavaScript、配列操作(map関数とforEach関数)

今回は、forEach関数とmap関数について解説していきます。

【forEach関数】

以下のような配列があるとします。

const array = ['a', 'b', 'c'];

ここで、forEach関数を使っていきます。

array.forEach(currentValue=> console.log(currentValue*2));

すると、ディベロッパツールでconsoleを見てみると

2a
2b
2c

と出てきます。では、実際にforEach関数を自分で作ってみます。すると、

let callback = (currentValue) => console.log(currentValue * 2);

function forEach(callback) {
 for (index in array) {
  callback(array[index]);
 }
 /*もしくは
 for (value of array) {
  callback(value)
 }
 */
}

と表せるのです。

【map関数】

forEach関数の時と同様に、以下のような配列があるとします。

const array = ['a', 'b', 'c'];

ここで、map関数を使っていきます。

const resultArray = array.map(currentValue => 
 return currentValue * 2;
);
console.log(resultArray);

すると、consoleを見てみると

['2a', '2b', '2c']

と出てきます。では、同様にmap関数を自分で作ってみます。すると、

let callback = (currentValue) => {
 currentValue * 2;
}

function map(callback) {
 const anotherArray = [];
 for (index in array) {
  let result = callback(array[index]);
  anotherArray.push(result);
  }
  return anotherArray;
}  

と表せます。

【まとめ】

map関数はもともとある配列の中身を一つ一つ処理して新しく配列を作る関数ということが分かります。                         それに対し、forEach関数は直接配列の中身を処理しているということが分かります。  

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です