LoginSignup
0
2

More than 5 years have passed since last update.

ES2015 mapとset

Last updated at Posted at 2017-03-02

mapオブジェクト

オブジェクトを格納するためのオブジェクトという認識。

mapオブジェクトの生成

//オブジェクトを作成する
const teacher1 = {name:"shinichi"};
const teacher2 = {name:"noguchi"};
const teacher3 = {name:"madoka"};

//作成したそれぞれのオブジェクトに値を割り当てる
const mapObj = new Map([
  [teacher1,"国語"],
  [teacher2,"英語"],
  [teacher3,"数学"]
]);

mapオブジェクトが特定のキーを保持しているかを判定

if (mapObj.has(teacher1)) {
  //マップオブジェクトがteacher1のキーを持っていたら。  
}

mapオブジェクトが保有するオブジェクトの個数を取得

console.log("teacherの数:" + mapObj.size); 

mapオブジェクトにオブジェクトを追加

const teacher4 = {name:"saito"};
mapObj.set(teacher4,"理科");

mapオブジェクト内の特定のオブジェクトの値を特定

mapオブジェクト.get(オブジェクト名)で何の値を紐づけられているかを確認することができる。

console.log("teacher1の担当:" + mapObj.get(teacher1)); //teacher1の担当:国語

mapオブジェクトのすべての値を取得する。

keyを全部取得。keys()。

const keys = mapObj.keys(); 
for (let key of keys) {
    console.log("キーたち:" + key);
}

全部の値を取得。values()。

const values = mapObj.values(); 
for (var value of values) {
    console.log("値たち:" + value);
}

すべての要素(キーと値の対応関係)を取得する。entries()。

for (let teacher of mapObj.entries()){
  console.log("ティーチャー名:" + teacher[0].name + "");
  console.log("担当教科は:" + teacher[1]);
}

mapオブエジェクトから特定の要素を削除

mapObj.delete(teacher2);

for (let teacher of mapObj.entries()){
  console.log("残ったティーチャー:" + teacher[0].name); //残ったティーチャーはshinichiとmadokaとsaitoになった。
}

setオブジェクト

set(集合)の意味。配列とは異なり、重複した値を格納することができない。

setオブジェクト生成

const subject = new Set();

値を追加

subject.add("数学");
subject.add("理科");

値の取得、その1

for (let value of subject.values()) {
    console.debug(value); 
}

値の取得、その2

for (let value of subject.entries()) {
    console.debug(value); 
}

0
2
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
2