The difference between Map and Set in ES6

Map

The representation of the default object in JS is {}, which is a set of key-value pairs, but the key must be a string.
In order to use Number or other data types as keys, the ES6 specification introduces a new data type Map.
Map is a structure of a set of key-value pairs with extremely fast search speed. Initializing the Map requires a two-dimensional array, or directly initializing an empty Map.

Use Map to implement a set of transcripts:

 

var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
m.get('Michael'); // 95

Map has the following methods:

 

var m = new Map(); // 空Map
m.set('Adam', 67); // 添加新的key-value
m.set('Bob', 59);
m.has('Adam'); // 是否存在key 'Adam': true
m.get('Adam'); // 67
m.delete('Adam'); // 删除key 'Adam'
m.get('Adam'); // undefined

Since a key can only correspond to one value, a key is put into value multiple times, and the following value will wash out the previous value:

var m = new Map();
m.set('Adam', 67);
m.set('Adam', 88);
m.get('Adam'); // 88

Set

Set is also a collection of a set of keys, similar to Map. But the difference is that Set does not store value, and its key cannot be repeated .
To create a Set, you need to provide an Array as input, or create an empty Set directly:

 

var s1 = new Set(); // 空Set
var s2 = new Set([1, 2, 3]); // 含1, 2, 3

Repeated elements will be automatically filtered in the Set (Note: the number 3 and the string '3' are different elements) :

 

var s = new Set([1, 2, 3, 3, '3']);
s; // Set {1, 2, 3, "3"}

Set has the following methods:

 

//通过add(key)方法可以添加元素到Set中,可以重复添加,但不会有效果
s.add(4);
s; // Set {1, 2, 3, 4}
s.add(4);
s; // 仍然是 Set {1, 2, 3, 4}

//通过delete(key)方法可以删除元素
var s = new Set([1, 2, 3]);
s; // Set {1, 2, 3}
s.delete(3);
s; // Set {1, 2}


add(value):添加某个值,返回Set结构本身。 
delete(value):删除某个值,返回一个布尔值,表示删除是否成功。 
has(value):返回一个布尔值,表示该值是否为Set的成员。 
clear():清除所有成员,没有返回值。

to sum up

1. The Map object is a collection of key-value pairs, similar to a JSON object, but the key can be not only a string but also various other types of values, including objects, which can become Map keys.

var map = new Map();
var obj = { name: '小缘', age: 14 };
map.set(obj, '小缘喵');
map.get(obj); // 小缘喵
map.has(obj); // true
map.delete(obj) ;// true
map.has(obj); // false

2. The Set object is similar to an array, and the values ​​of the members are unique

 

Guess you like

Origin blog.csdn.net/asteriaV/article/details/115321762