ES6 the Map and Set

The concept of the difference between a collection and an array of well

In fact, the collection is an array, but the array index is a numeric type. When you want to use non-numeric type as an index, the array will not be able to meet the needs.

Map set and a plurality of keys may be stored - value pairs (key-value), Set can store a set of a plurality of elements.

Set the Map and generally do not individually through the elements therein. Map typically requires frequent access for storing data, Set typically used to determine whether there is a value which.

ES 5 in the simulation method of the Map and Set

5 in the ES, and Map Set not set, the object is generally used to simulate both set as the key attributes of the objects (Key), to an attribute value as the value (value), i.e. in  property: property-value simulated  key-value form embodied as follows:

Map of simulation key to the collection:

// 创建一个 Map 对象
var map = Object.create(null);

// 添加属性和属性值, 即 添加 key 和 value map.key1 = 'value 1'; map.key2 = {}; // 取得 key 对应的 value console.log(map.key1); // "value 1" console.log(map.key2); // "Object {}"

Analog Set:

// 创建一个 Set 对象
var set = Object.create(null);

// 添加属性和属性值, 即 添加 key 并令其值为 true, 即表示这个key存在于集合中 set.key = true; // 判断 key 是否存在, 然后进行下一步的操作 if(set.key) { ... }

The two objects in the simulation using a set of the defect

  1. Due to the nature of the object name must be a string, not a string if passed will cast into the corresponding string type (knowledge casts can see aspects of this article click )
  2. Usually if statement to determine whether there is a key in the collection, when the value corresponding to the key is false or may be cast to false, the statement that if the key does not exist, but the fact is there, but value = false only.

ES6 in Map and Set collections

Map

Map is stored in key-value in the form of key-value pairs, where the key and value may be any type, i.e. the object can be used as key. This manner than an object to simulate a lot of flexibility to the

Map of creation and initialization

  1. You can use the new Map () constructor to create an empty Map
// 创建一个空的 Map 
let map  = new Map();
  1. Can also pass the Map () constructor, an array to create and initialize a Map. Incoming array is a two-dimensional array, where each sub-array has two elements, the former will be used as key, which will as the value, thus forming a key, for example key-value:
// 用数组来创建一个 非空的 Map 

let array = [ // 定义一个二维数组,  数组中的每子都有两个元素
    ['key1' ,  'value 1'], // key 是 字符串 "key1", value 是字符串 "value 1" [{} , 10086] , // key 是个对象, value 是数值 10086 [ 5, {} ] // key 是个数值类型, value 是对象 ]; let map = new Map(array); // 将数组传入 Map 构造函数中

Map available methods

  1. set(key, value): To this was added a key-value pair
  2. get(key): If there key return undefined
  3. has(key): Returns a Boolean value
  4. delete(key): Deleted successfully return true, if the key does not exist or delete false failure returns
  5. clear(): Clear all elements

size attribute, attribute value for the number of key-value map

Traversal method forEach ()

ForEach array and method similar to the callback function contains three parameters, the key, and the collection itself Map this method call

map.forEach(function(value,  key,  ownerMap){
    console.log(key,  value); // 每对键和值 console.log(ownerMap === map); // true });
 

Set collection

Set Map and the biggest difference is not only the key and key value, it is generally used to determine an element (key) is present in them.

Creation and initialization method, similar and Map

Either create an empty set can also be used to initialize an array of non-empty set and the Map is different is that the array is one-dimensional array, each element will be the set of keys for example..:

// 创建一个数组
let array = [1, 'str'];      // 一维数组 // 用数组来初始化 set let set = new Set(array);
 

set method

  1. add(key): Add an element to the set, if the incoming number of parameters, only the first one will join in
let set = new Set();
set.add(1, 2, 3); console.log(set.has(1), set.has(2), set.has(3)); // true false false 可以看到只有第一个参数被加入进了 set
  1. has(key)
  2. delete(key)
  3. clear()

Traversal methods forEach

Map and forEach method is similar to the callback function parameter is 3 (value, key, ownerSet). Logically, because this set is not only a key value, then the value will fall should not be there this parameter function, why this value parameters still exist? Probably because the callback function parameters forEach method of arrays and Map are three, if for Set and change the parameters, it will lose the consistency. For this reason ......

Well, since there is no value, then the value of the value of what is it? The answer is the same and the key. We can equate the value and key. The following code can verify this statement.

set.forEach(function(value,  key,  ownerSet){
    console.log(value === key,  set === ownerSet);   // true true });


WeakSet 和 WeakMap

Two sets before the name of both sets than before are added  Weak, this  Weak can be directly translated , this means that weak weak references, then the front without the Weak Set Map is not weak, is strong, and this strong It refers to the strong references.

The difference between Set and Map

  • Let me talk about the difference between the surface layer:
  1. Key weak version of the collection  can only be an object , no limitation on the type of value.
  2. ForEach method is not a weak version of the collection, there is no method for in, nor can initialize the array (being given).
  3. The method is less available WeakSet weak version only.  add, has, delete The method can be used; WeakMap only  set, has, get, delete method available.
    • The fundamental difference between
      weak and strong set of versions of their respective versions of the fundamental differences in the strength for the referenced object, and the object refers to a  key  position of the object, i.e., a case where the object to the key.

Strength version for key mechanism is a reference to the time of objects as follows:

The target is set to key, to save the object in the collection references. When this object has no other references to the time that only the collection also cited the object when a collection of loosely typed will give up a reference to the object , this object is removed from the set, and did not let it continue to exist in the collection, and some "ruthless" means; but also strongly typed collection has been preserved in a reference to the object, put it up on the set in. this is [WeakSet and WeakMap] fundamental difference with [Set and Map] is.

Note that this mechanism only affects the key, and the object value of the position of the binding regardless of whether there are other references, WeakMap will not give up the object. Only the object key bindings that position when there are no other references, will the key and value are discarded. decision rests with the key position.

The main use of weak version of a collection

If the version of the collection can be used where needed life-cycle management, such as saving a reference to a DOM object, if a DOM object is used up, there is no other references, then it should be garbage, in order to avoid a memory leak, then the weak version the collection on the most suitable for the preservation of such objects.

Note: four kinds of set are ordered, i.e., elements are added to it in order to save the sequence is internal to an array initialized to set the same, according to the position in the array are sequentially added to the collection.

Original blog link: https://www.cnblogs.com/shikaka/p/10576531.html

 

Guess you like

Origin www.cnblogs.com/xiaoeshuang/p/12176141.html