Home  >  Article  >  Web Front-end  >  Introduction to the usage of Map in ES6 (code example)

Introduction to the usage of Map in ES6 (code example)

不言
不言forward
2018-11-14 16:16:594337browse

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.

Overview

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']

Initialization

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}

Add

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关联的值");

Get## The size of #Map
myMap.size    // 3

Get

myMap.get(keyString)   // "和键'a string'关联的值"
myMap.get(keyObj)     // "和键keyObj关联的值"
myMap.get(keyFunc)      // "和键keyFunc关联的值"

Whether it contains

myMap.has(keyString)  // true
myMap.has('1')  // false

Delete

myMap.delete(keyString)  // true
myMap.delete('')  // false

Traverse

myMap.forEach(m=>{console.log(m)})
// 和键'a string'关联的值
//  和键keyObj关联的值
//  和键keyFunc关联的值

Get the iterator

let entries=myMap.entries()
entries.next().value // 和键'a string'关联的值
entries.next().value//  和键keyObj关联的值
entries.next().value//   和键keyFunc关联的值

Get key iterator

let keys=myMap.keys()
keys.next().value //  "a string"
keys.next().value//  function () {}
keys.next().value//   {}

Get value iterator

let values=myMap.values()
values.next().value // 和键'a string'关联的值
values.next().value//  和键keyObj关联的值
values.next().value//   和键keyFunc关联的值

Clear

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete