Map

时间:2020-05-06
本文章向大家介绍Map,主要包括Map使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Map

Prior to ES6, when we require the mapping of keys and values, we often use an object. It is because the object allows us to map a key to the value of any type.

在ES6之前,当我们需要键和值的映射时,经常使用一个对象。这是因为该对象允许我们将键映射到任何类型的值。

ES6 provides us a new collection type called Map, which holds the key-value pairs in which values of any type can be used as either keys or values. A Map object always remembers the actual insertion order of the keys. Keys and values in a Map object may be primitive or objects. It returns the new or empty Map. Maps are ordered, so they traverse the elements in their insertion order.

ES6为我们提供了一种称为Map的新集合类型,其中包含键-值对,其中任何类型的值都可以用作键或值。Map对象始终记住键的实际插入顺序。Map对象中的键和值可以是原始或对象。它返回新的或空的Map。Map是有序的,因此它们按其插入顺序遍历元素。

Syntax

For creating a new Map, we can use the following syntax:

var map = new Map([iterable]);  

The Map () accepts an optional iterable object, whose elements are in the key-value pairs.

Map()接受一个可选的可迭代对象,该对象的元素在键值对中。

Map Properties

Properties Description
Map.prototype.size This property returns the number of key-value pairs in the Map object.

This property returns the number of key-value pairs in the Map object.

让我们简要地了解一下Map对象的上述属性。

Map.prototype.size

It returns the number of elements in the Map object.

它返回Map对象中的元素数。

Syntax

Map.size

var map = new Map();  
    map.set('John', 'author');  
    map.set('arry', 'publisher');  
    map.set('Mary', 'subscriber');  
    map.set('James', 'Distributor');  
    
console.log(map.size); 
output

4

Map Methods

The Map object includes several methods, which are tabulated as follows:

Map对象包括几种方法,其列表如下:

Methods Description
Map.prototype.clear() It removes all the keys and values pairs from the Map object.它从Map对象中删除所有键和值对
Map.prototype.delete(key) It is used to delete an entry.用于删除条目
Map.prototype.has(value) It checks whether or not the corresponding key is in the Map object.它检查相应的键是否在Map对象中
Map.prototype.entries() It is used to return a new iterator object that has an array of key-value pairs for every element in the Map object in insertion order.它用于返回一个新的迭代器对象,该对象具有按插入顺序排列的Map对象中每个元素的键值对数组
[Map.prototype.forEach(callbackFn, thisArg]) It executes the callback function once, which is executed for each element in the Map.它只执行一次回调函数,该回调函数针对Map中的每个元素执行
Map.prototype.keys() It returns an iterator for all keys in the Map.它返回Map中所有键的迭代器
Map.prototype.values() It returns an iterator for every value in the Map.它为Map中的每个值返回一个迭代器。

Weak Maps

Weak Maps are almost similar to normal Maps except that the keys in weak maps must be objects. It stores each element as a key-value pair where keys are weakly referenced. Here, the keys are objects, and the values are arbitrary values. A Weak Map object only allows the keys of an object type. If there is no reference to a key object, then they are targeted to garbage collection. In weak Map, the keys are not enumerable. So, there is no method to get the list of keys.

弱映射几乎与普通映射相似,不同之处在于弱映射中的键必须是对象。它将每个元素存储为键-值对,其中键被弱引用。在这里,键是对象,值是任意值。弱映射对象仅允许使用对象类型的键。如果没有对关键对象的引用,则它们将针对垃圾回收。在弱Map中,键不可枚举。因此,没有方法来获取键列表。

A weak map object iterates its elements in the insertion order. It only includes delete(key), get(key), has(key) and set(key, value) method.

弱映射对象按插入顺序迭代其元素。

Let us try to understand the illustration of the weak Map.

Example
let wp = new WeakMap();   
let obj = {};   
console.log(wp.set(obj,"Welcome to javaTpoint"));    
console.log(wp.has(obj));
output
WeakMap { <items unknown> }
true

The for...of loop and Weak Maps

The for...of loop is used to perform an iteration over keys, values of the Map object. The following example will illustrate the traversing of the Map object by using a for...of loop.

for ... of循环用于对键(即Map对象的值)执行迭代。以下示例将通过使用for ... of循环来说明Map对象的遍历。

Example
var colors = new Map([   
   ['1', 'Red'],   
   ['2', 'Green'],   
   ['3', 'Yellow'],  
   ['4', 'Violet']   
]);  
  
for (let col of colors.values()) {  
    console.log(col);  
}  
  
console.log(" ")  
  
for(let col of colors.entries())   
console.log(`${col[0]}: ${col[1]}`); 
Output
Red
Green
Yellow
Violet

1: Red
2: Green
3: Yellow
4: Viole

Iterator and Map

An iterator is an object, which defines the sequence and a return value upon its termination. It allows accessing a collection of objects one at a time. Set and Map both include the methods that return an iterator.
迭代器是一个对象,它定义序列和终止时的返回值。它允许一次访问一组对象。
Set和Map都包含返回迭代器的方法

Iterators are the objects with the next() method. When the next() method gets invoked, the iterator returns an object along with the "value" and "done" properties.
迭代器是具有next()方法的对象。当调用next()方法时,迭代器将返回一个对象以及“value”和“done”属性

Let us try to understand some of the implementations of iterator along with the Map object.
让我们尝试了解一些迭代器以及Map对象的实现

Example-1
var colors = new Map([
	['1', 'Red'],
	['2', 'Green'],
	['3', 'Yellow'],
	['4', 'Violet']
]);

var iter = colors.values();
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
output
{ value: 'Red', done: false }
{ value: 'Green', done: false }
{ value: 'Yellow', done: false }
Example-2
var colors = new Map([
	['1', 'Red'],
	['2', 'Green'],
	['3', 'Yellow'],
	['4', 'Violet']
]);

var iter = colors.entries();
console.log(iter.next());
console.log(iter.next());
console.log(iter.next());
output
{ value: [ '1', 'Red' ], done: false }
{ value: [ '2', 'Green' ], done: false }
{ value: [ '3', 'Yellow' ], done: false }
Example-3
var colors = new Map([   
   ['1', 'Red'],   
   ['2', 'Green'],   
   ['3', 'Yellow'],  
   ['4', 'Violet']   
]);  
  
var iter = colors.keys();  
console.log(iter.next());  
console.log(iter.next());  
console.log(iter.next());
Output
{ value: '1', done: false }
{ value: '2', done: false }
{ value: '3', done: false }

原文地址:https://www.cnblogs.com/PrimerPlus/p/12837824.html