📘Map

🚧 under construction

breadcrumb 🚧

Map

雖然 Object 與 Map 都是 JS 用來實現 Dictionary 的方法,但它們存在基本的不同點。

Maps vs. Objects

featureMapObject
  • ✅ use [...map] to convert into Array.

  • for(const [key, value] of map){...}

  • for(const key of map.keys()){...}

  • for(const value of map.values()){...}

  • ✅ map.forEach((value, key) => {...})

keys

can be any value (including functions, objects, or any primitive).

must be either String or Symbol.

✅ number of items in a Map

❌ no such property

Map ⇔ Array

// Array => Map
const map = new Map([['key1', 'value1'], ['key2', 'value2']])

// Map => Array<[Key, Value]>
[...map]        // [['key1', 'value1'], ['key2', 'value2']]

// Map => Array<Value>
[...map.values()]

Other Topics

Last updated