LoginSignup
1
1

More than 1 year has passed since last update.

【javascript】Map, Set

Last updated at Posted at 2021-11-25

Map, Set

  • データを管理するための入れ物。
  • コレクションともいう
  • ES6から採用された

ObjectとMapの違い

Object Map
key 文字列 制約なし(数値、関数、オブジェクトなど)
for..in ×
for..of ×
  • mapはEntriesという格納場所がありそこでデータを管理している。 スクリーンショット 2021-11-25 15.24.33.png
const map = new Map();

//オブジェクトをkeyに設定できる。
const key = {}
map.set(key, 'value');
console.log(map.get(key));

>>> value

//関数をkeyに設定できる。
const key2 = function(){};
map.set(key2, 'value2');
console.log(map.get(key2));

>>> value2

// 数値もkeyに設定できる。
const key3 = 3;
map.set(key3, 'value3');
console.log(map.get(key3));

>>> value3

//値の削除
map.delete(key3)
console.log(map.get(key3))

>>> undefined


//for..ofの確認
for(const [k, v] of map){
    console.log(k, v)
}

>>> {}:'value'
>>> ():'value2'

ArrayとSetの違い

Array Set
重複値 ×
for..in ×
for..of
添字[] ×

const key = {}
const key2 = function(){};

const s = new Set()

//値の重複ができないことの確認
s.add(key); //同じ値をsに追加している。
s.add(key);

//for...ofで確認
for(const k of s){
    console.log(k)
}

>>> {} //一つしか出力されなかった。

//値の削除
s.delete(key2)
console.log(s.key2)
>>> undefined


//値の存在確認(mapでも使える。)
console.log(s.has(key2))
>>> false

//添字を使えるようにsetをarrayに変換
const arry = Array.from(s)
// arry = [...s]スプレッド構文でも良い。
console.log(arry[0]) 
1
1
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
1
1