LoginSignup
4
2

More than 5 years have passed since last update.

Mapでの連想配列を定義と for of ループと分割代入

Last updated at Posted at 2018-08-01

連想配列を JavaScriptオブジェクトで使うのをやめて極力 Map を使うやり方にシフトしたいのでメモ。
https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Map

const mapTest = new Map([
    ['key1', 123], 
    ['key2', 456]
]);

mapTest.get('key1') == 123
mapTest.get('key2') == 456

for...of ループは各処理で [キー, 値] の配列を返すので、分割代入を利用して以下のようにそれぞれの値を取得することができる。

for (const [key, value] of mapTest) {
    console.log(`${key} : ${value}`);
}

// 出力結果:
// key1 : 123
// key2 : 456

それぞれのキーを順番に巡回したいときは Maps.keys() メソッドが、Mapオブジェクト内の要素に対して挿入順に keys を含む新しい Iterator オブジェクトを返す機能をもっているので以下のように書くことができる。ただ大抵はkeyとvalueの組み合わせで使うので上記のループで事足りるかもしれない。

for (const key of mapTest.keys()) {
    console.log(key);
}

// 出力結果:
// key1
// key2
4
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
4
2