Home > Article > Web Front-end > Introduction to the usage of Map in ES6 (code example)
This article brings you an introduction to the usage of Map in ES6 (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Map is also a new data structure. It is actually often used in js. For example, in the chestnut below, we often use an object like this. Rather than saying that it is an object, it is actually More like a Map, but compared to a real Map, this is still a bit weak,
let color={ "red":"#FF0000", "green":"#00FF00", "blue":"#0000FFF" } color['red']
new Map([iterable])
Initializing a Map has an optional parameter, which must be an iterable Objects, iterable objects include String, Array, Array-Like obejct (Arguments, NodeList), Typed Array, Set, Map and user-defined iterable objects.
Array
new Map([[1,2],[3,4]]) // Map(2) {1 => 2, 3 => 4}
Compared with the object as Map, the key of Map can be any value, even NaN
var myMap = new Map(); var keyObj = {}, keyFunc = function () {}, keyString = "a string"; // 添加键 myMap.set(keyString, "和键'a string'关联的值"); myMap.set(keyObj, "和键keyObj关联的值"); myMap.set(keyFunc, "和键keyFunc关联的值");
myMap.size // 3
myMap.get(keyString) // "和键'a string'关联的值" myMap.get(keyObj) // "和键keyObj关联的值" myMap.get(keyFunc) // "和键keyFunc关联的值"
myMap.has(keyString) // true myMap.has('1') // false
myMap.delete(keyString) // true myMap.delete('') // false
myMap.forEach(m=>{console.log(m)}) // 和键'a string'关联的值 // 和键keyObj关联的值 // 和键keyFunc关联的值
let entries=myMap.entries() entries.next().value // 和键'a string'关联的值 entries.next().value// 和键keyObj关联的值 entries.next().value// 和键keyFunc关联的值
let keys=myMap.keys() keys.next().value // "a string" keys.next().value// function () {} keys.next().value// {}
let values=myMap.values() values.next().value // 和键'a string'关联的值 values.next().value// 和键keyObj关联的值 values.next().value// 和键keyFunc关联的值
mySet.clear()
The above is the detailed content of Introduction to the usage of Map in ES6 (code example). For more information, please follow other related articles on the PHP Chinese website!