Map 对象保存键值对,并且能够记住键的原始插入顺序。任何值(对象或者原始值) 都可以作为一个键或一个值。

:::tips 键的相等: sameValueZeros: NaN equals NaN, -0 equals +0 :::

Map vs Object

  • 一个 Object 有一个原型, 原型链上的键名有可能和你自己在对象上的设置的键名产生冲突
  • 一个 Map的键可以是任意值,包括函数、对象或任意基本类型, 一个Object 的键必须是一个 String 或是Symbol
  • Map 中的 key 是有序的。因此,当迭代的时候,一个 Map 对象以插入的顺序返回键值。一个 Object 的键是无序的
  • Map 的键值对个数可以轻易地通过size 属性获取, Object 的键值对个数只能手动计算
  • Map 在频繁增删键值对的场景下表现更好。

Map的方法

  • The clear() method removes all elements from a Map object.
    • Return undefined
  • The delete() method removes the specified element from a Map object by key.

    1. const map1 = new Map();
    2. map1.set('bar', 'foo');
    3. console.log(map1.delete('bar'));// true
    4. console.log(map1.has('bar'));// false
  • get()

    let myMap = new Map();
    myMap.set('bar', 'foo');
    myMap.get('bar');   // Returns "foo"
    myMap.get('baz');   // Returns undefined
    
  • has() ```javascript let myMap = new Map() myMap.set(‘bar’, “foo”)

myMap.has(‘bar’) // returns true myMap.has(‘baz’) // returns false


- The `set(key,value)` method adds or updates an element with a specified key and a value to a Map object.
   - Return the `Map` object

**Iteration methods**

- Map.prototype.keys()
   - Returns a new Iterator object that contains the keys for each element in the Map object in insertion order.
```javascript
var myMap = new Map();
myMap.set('0', 'foo');
myMap.set(1, 'bar');
myMap.set({}, 'baz');

var mapIter = myMap.keys();
console.log(mapIter.next().value); // "0"
console.log(mapIter.next().value); // 1
console.log(mapIter.next().value); // Object
  • Map.prototype.values()
    • Returns a new Iterator object that contains the values for each element in the Map object in insertion order.
  • Map.prototype.entries()
    • Returns a new Iterator object that contains [key, value] for each element in the Map object in insertion order. ```javascript let myMap = new Map() myMap.set(‘0’, ‘foo’) myMap.set(1, ‘bar’) myMap.set({}, ‘baz’)

let mapIter = myMap.entries() console.log(mapIter.next().value) // [“0”, “foo”] console.log(mapIter.next().value) // [1, “bar”] console.log(mapIter.next().value) // [Object, “baz”] ```

  • Map.prototype.forEach(callbackFn[,thisArg])
    • Calls callbackFn once for each key-value pair present in the Map object, in insertion order. If a thisArg parameter is provided to forEach, it will be used as the this value for each callback.