A, the Set

A set is an ordered list, similar to an array, but with unique values. Through the set set, the data can be accessed quickly and various discrete values can be tracked more effectively.

1. Common methods

// @add: add elements
// @delete: removes the element
// @clear: clear all elements in set
// @has: determines whether a value exists in the set
// size property: Gets the current number of elements in the collection

let set = new Set(a);let k1 = {};
let k2 = {};

set.add(7);
set.add('7');

set.add(k1);
set.add(k2);

set.add(7);                 // Repeat - this call will be ignored

console.log(set.size);      / / 4
console.log(set.has(7));    // true

console.log(set.get(8));    // undefined

set.delete(7);

console.log(set.has(7));    // false
console.log(set.size);      / / 3

set.clear();

console.log(set.has('7')) :// false
console.log(set.size);       / / 0

set.add(+0).add(-0);
console.log(set.size);       / / 1

set.clear();

set.add(NaN).add(NaN);
console.log(set.size);       / / 1

set.clear();

set.add(undefined).add(undefined);
console.log(set.size);       / / 1
Copy the code

2. The initialization

let set = new Set([1.2.3.4.5.5.5.5]);
console.log(set.size);     / / 5
Copy the code

3. Traversal method

// @keys(): returns the traversal of the key name
// @values(): returns a traversal of key values
// @entries(): Returns a traverser for key-value pairs
// @foreach (): uses the callback function to iterate over each member

// Keys and values behave the same as each other because the set method has the same key name and value.
let set = new Set(['a'.'b'.'c']);
for (let item of set.keys()) {
    console.log(item);
}
// a
// b
// c

for (let item of set.values()) {
    console.log(item);
}
// a
// b
// c

for (let item of set.entries()) {
    console.log(item);
}
// ['a', 'a']
// ['b', 'b']
// ['c', 'c']

for (let item of set) {
    console.log(item);
}
// a
// b
// c

let set = new Set([1.2.3]);
set.forEach((value, key, ownerSet) = > {
  console.log(key + ' ' + value);
  console.log(ownerSet === set)
})

/ / 1 1
// true
2 / / 2
// true
/ / 3. 3
// true

let set = new Set([1.2.3]);
let processor = {
   output(val) {
     console.log(val);
   },
   process(dataSet) {
     dataSet.forEach(function(val) {
        this.output(val);
     }, this);
   }
}

processor.process(set);

/ / 1
/ / 2
/ / 3

Copy the code

4. The application

// It is easy to implement Union, intersection, and Difference using Set.
let a = new Set([1.2.3]);
let b = new Set([4.3.2]);

/ / and set
let union = new Set([...a, ...b]);
// Set {1, 2, 3, 4}

/ / intersection
let intersect = new Set([...a].filter(x= > b.has(x)));
// Set {2, 3}

// The difference set a - b
let difference = new Set([...a].filter(x= >! b.has(x)));// Set { 1 }

// set b - a
let difference = new Set([...b].filter(x= >! a.has(x)));// Set { 4 }
Copy the code

5. Summary:

The number 7 and the string ‘7’ are two separate elements. 2. The key name of a set can be an object, so k1 and k2 are not converted to strings. They are independent elements. 3. If the key name passed in when the get method is called does not exist in set, undefined is returned. 4. There are no duplicate values in the set, which can be used for array de-duplication. 5. +0 and -0 in Set are considered equal; NaN and NaN are not identical, but NaN and NaN are considered equal in Set, so only one can exist; 7. Undefined and undefined are identical, so they cannot be repeated; ForEach (); forEach (); forEach (); 9. The third argument ownerSet is equal to set; 10. The second argument to forEach as a reference to this in the callback; 11. A set cannot be accessed by an index, but must be converted to an array. 12. Set traversal order is insert order; 13. An instance of a set structure can be traversed by default. The default traverser generator is its values method, so you can omit the values method. 14. Array-specific methods (such as Map, filter, and reduce) need to convert a map to an array before using it.

Second, the Map

Because attribute names in objects can only be strings, ES6 extends the Map type. A Map type is an ordered list of key-value pairs in which key names and corresponding values support all data types.

1. Common methods:

// @set: add key-value pairs
// @get: gets the value of the attribute passed in
// @delete: removes key-value pairs
// @clear: remove all key-value pairs in the Map set
// @has: checks whether the specified key name exists in the Map collection
// size attribute: find the number of key-value pairs in the Map set


let map = new Map(a);let k1 = {}, key2 = {};

map.set(k1, 5);
map.set(k2, 40);

map.set('name'.'xiaoming');
map.set('age'.25);

console.log(map.size);  / / 4

console.log(map.has('name'));  // true
console.log(map.get('name'));  // xiaoming

map.set('name'.'xiaohong');
console.log(map.has('name'));  // true
console.log(map.get('name'));  // xiaohong


console.log(map.delete(k1));

console.log(map.has(k1));  // false
console.log(map.get(k1));  // undefined
console.log(map.size);     / / 3

map.clear();
console.log(map.has(name));  // false
console.log(map.get(name));  // undefined
console.log(map.size);     / / 0
Copy the code

2. The initialization

let map = new Map([['name'.'xiaoming'], ['age'.25]]);

console.log(map.has('name'));  // true
console.log(map.get('name'));  // xiaoming
console.log(map.has('age'));   // true
console.log(map.get('age'));   / / 25
Copy the code

3. Traversal method

// @keys(): returns the traversal of the key name
// @values(): returns a traversal of key values
// @entries(): Returns a traverser for all members
// @foreach (): traverses all Map members

let map = new Map([['name'.'xiaoming'], ['age'.25]]);
for (let key of map.keys()) {
    console.log(key);
}
// 'name'
// 'age'

for (let value of map.values()) {
    console.log(value);
}
// 'xiaoming'
/ / 25

for (let [key, value] of map.entries()) {
    console.log(key, value);
}
// 'name' 'xiaoming'
// 'age' 25

for (let [key, value] of map) {     // Equivalent to using map.entries()
    console.log(key, value);
}
// 'name' 'xiaoming'
// 'age' 25

map.forEach(function(value, key, ownerMap) {
    console.log(key + ' ' + value);
    console.log(ownerMap === map);
});

// name xiaoming
// true
// age 25
// true
Copy the code

Summary:

1. Attribute names in map can be of any type and are not cast to strings (objects do); 2. The size attribute in MAP is similar to that in SET. Its value is the number of key-value pairs in the set. 3. We initialize the Map collection by passing a two-dimensional array to the Map constructor. The subarray contains the key name and the value of a key-value pair. 4. If you add the same key name to the Map, the Map overwrites the original key name. 5. As you can see from the above examples, the default Map iterator interface (symbol. iterator property) is the entries method; 6. The forEach() method in Map is similar to the forEach() method in Set sets and arrays; 7. During traversal, the corresponding information is passed to the callback function of forEach() in the order in which the key/value pairs are inserted into the Map collection, and the callback function is passed in the order in which the numeric index values are inserted into the array. 8. You can also specify the second argument to forEach() as the this value of the callback.

Set, Map, array, object comparison

let set = new Set(a);let map = new Map(a);let array = [];
let obj = {};

/ / to add
set.add({age: 25});
map.set('age'.25);
array.push({age: 25});
obj['age'] = 25; // obj.age = 25

/ / delete
set.forEach(item= > item.age ? set.delete(item) : ' ');
map.delete('age');
let index = array.findIndex(item= > item.age);
array.splice(index, 1);
delete obj['age']; ordelete obj.age
delete obj; // Delete the entire object

/ / change
set.forEach(item= > item.age ? item.age = 26 : ' ');
map.set('age'.26);
array.forEach(item= > item.age ? item.age = 26 : ' ');
/ / or
array.map(item= > item.age ? item.age = 26 : ' '); // Array is modified
obj['age'] = 26; // obj.age = 26

/ / check
set.has({age: 25});
map.has('age');
array.find(item= > item.age);
'age' in obj
Copy the code
// The difference between Map and Object
An Object key can only be a string or a symbol, but a Map key can be any value.
// 2. The keys in Map are ordered, while the keys in object are not.
// 3. Map key/value pairs can be obtained directly from the size property, while Object needs to be calculated manually.
// 4. Object has its own prototype, and the key name on its Object may be the same as the key name on the prototype chain.
// 5. Map can iterate directly, but Object cannot.
Copy the code
// The difference between Set and Array
// 1. Uniqueness: Elements in a Set are unique, and elements in an Array can be repeated.
// 2. Length: Set uses the size attribute to obtain the Set length, Array uses the length attribute to obtain the Set length.
// 3. Obtain elements: Array can be directly indexed, and set can only be traversed.
// 4. Add elements: Array adds values via push() or index, and Set adds values via add(). And return the Set object itself after addition, you can make chain calls.
// 5. Delete elements: Array deletes elements using splice and Set deletes elements using delete().
// 6. Clear elements: Array is cleared with array.length = 0, while Set is cleared with clear().
// 7. Query: Array uses indexOf() or includes() to check whether a value exists, and Set is implemented using has().
Copy the code

Summary:

  1. Map has a low cost. Therefore, Map is preferred.
  2. If you want unique data, consider using a set.
  3. In the future, Set and Map should be used as much as possible, and arrays and objects should not be used except in special cases.

4, Set, Map, array, object conversion

// Set is converted to an array
let set = new Set(['a'.'b'.'c']);
let arr = [...set];    // let arr = array. from(set)
// ['a', 'b', 'c']

// Array to Set: pass the array to the Set constructor
let arr = [1.2.3.4.5];
let set = new Set(arr);
{1, 2, 3, 4, 5}

// Map to array
const map = new Map(a); map.set(true.7).set({foo: 3},'abc']);
[...map] // [[true, 7], [{foo: 3}, ['abc']]]

// The array is converted to Map
new Map([true.7], [{foo: 3},'abc']]);
// Map { true => 7, Object { foo: 3} => ['abc']}

// Map to object (can only be converted if all Map keys are strings)
function strMapToObj(strMap) {
    let obj = Object.create(null);
    for (let [k, v] of strMap) {
        obj[k] = v
    }
    return obj;
}

const map = new Map().set('name'.'xiaoming').set('age'.25);
strMapToObj(map); // { name: 'xiaoming', age: 25 }

// The object is converted to Map
function objToStrMap(obj) {
    let strMap = new Map(a);for (let k of Object.keys(obj)) {
        strMap.set(k, obj[k]);
    }
    return strMap;
}

objToStrMap({ name: 'xiaoming'.age: 25 });
// Map {'name' => 'xiaoming', 'age' => 25}
Copy the code

Summary:

A Set, a Map, or an array can be converted into an array. Grammar; 2.Map can be converted to objects only if all keys are strings.

Five, the summary

1. A Set is an ordered list containing multiple non-repeating values. The equivalence between values is determined by object.is () method. A Set is not a subclass of an array and cannot access values randomly. You can only check the existence of a specified value through the has() method, or see the number of values in a Set through the size property. 2. A Map is an ordered collection of multiple key-value pairs. The key names can support any data type. No type conversion is performed, and the number 7 and string ‘7’ can be used as two separate key names. Values of any type can be added to a collection through the set() method, all values in the collection can be retrieved through the get() method, and the number of values in the collection can be checked through the size attribute. 3. Compared with arrays and objects, Set and Map have better performance, faster code execution, simple code without redundancy, and easy maintenance, so they are preferred in project development.