The JS object itself is a key-value structure. Why does ES6 need to add Map? What is the difference between it and ordinary JS objects?
1. Map
1. Map constructor
Let’s look at the simple usage of Map first
// 字符串作为key, 和JS对象类似 var map = new Map() // set map.set('name', 'John') map.set('age', 29) // get map.get('name') // John map.get('age') // 29
With this code, it seems that it is not as concise as JS objects
But the power of Map is that its key can be of any type
// 对象作为key演示 var xy = {x: 10, y: 20} // 坐标 var wh = {w: 100, h: 200} // 宽高 var map = new Map() // set map.set(xy, '坐标') map.set(wh, '宽高') // get map.get(xy) // '坐标' map.get(wh) // '宽高'
The above demonstrates a Map using objects as keys. The following is an illustration
The Map constructor also supports passing arrays
var map = new Map([["name", "John"], ["age", "29"]]) // 遍历key for (var key of map.keys()) { console.log(key) // name, age }
2. Iteration
Use for of to iterate Map like Set, call map.keys() for keys, map.values() for values, and map.entries() for key-value entities
var map = new Map() // set map.set('name', 'John') map.set('age', 29) // get map.get('name') // 'John' map.get('age') // 29 // 遍历key for (var key of map.keys()) { console.log(key) } // 遍历value for (var val of map.values()) { console.log(val) } // 遍历实体 for (var arr of map.entries()) { console.log('key: ' + arr[0] + ', value: ' + arr[1]) } // 遍历实体的简写 for (var [key, val] of map.entries()) { console.log('key: ' + key + ', value: ' + val) }
3. Methods and properties
2. WeakMap
Differences from Map
Does not accept basic type values as key names
No keys, values, entries and size
There are following methods
The above is the entire content of this article, I hope you all like it.