はじめに
この記事はJS初級者が中級者を目指して学習した内容のメモであることをご承知おき下さい
2つのmap
JSにはひと口にmapといってもMapオブジェクトとmapメソッドの2つあり、異なる目的で使用される
Mapオブジェクト
Mapオブジェクトは、キーと値のペアを保持するためのコレクションこと。
オブジェクトと似ているがMapオブジェクトは任意のデータ型(オブジェクトを含む)をキーとして使用できる。
const myMap = new Map();
const key1 = 'key1';
const key2 = 0; // 任意のデータ型をキーとして使用できる
const key3 = {}; // 任意のデータ型をキーとして使用できる
myMap.set('key1', 'value1');
myMap.set('key2', 'value2');
myMap.set('key3', 'value3');
また、Mapオブジェクトは要素の挿入順を保持し、繰り返し処理が可能。
// Mapオブジェクトはfor..ofで繰り返し処理が可能
const myMap = new Map([
['key1', 'value1'],
['key2', 'value2'],
['key3', 'value3'],
]);
for(const map of myMap){
console.log(map); // ['key1', 'value1'] ['key2', 'value2'] ['key3', 'value3']
}
mapメソッド
mapメソッドは配列メソッドの一種で、配列の各要素に対して指定された関数を実行し、その結果を新しい配列として生成することができる。
元の配列を変更せずに、新しい配列を返すことができるのが特徴。
const array = [1, 2, 3, 4, 5];
const newArray = array.map(element => element * 2);
console.log(newArray); // [2, 4, 6, 8, 10]