Difference: 1. Set refers to the "set" structure, while Map refers to the "dictionary" structure; 2. Set stores elements in the form of "[value, value]", while Map stores elements in the form of "[value, value]" It is stored in the form of "[key, value]"; 3. Map can use get() to find a specific value by key and return it, but set cannot.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Brief description:
The difference between sets and dictionaries:
ES6 new one A new data structure, similar to an array, but the members are unique and unordered, with no duplicate values.
Set itself is a constructor used to generate Set data structure.
Set objects allow you to store unique values of any type, whether primitive values or object references.
const s = new Set() [1, 2, 3, 4, 3, 2, 1].forEach(x => s.add(x)) for (let i of s) { console.log(i) // 1 2 3 4 } // 去重数组的重复对象 let arr = [1, 2, 3, 2, 1, 1] [... new Set(arr)] // [1, 2, 3]
Note: When adding a value to Set, no type conversion occurs, so `5` and `"5"` are two different values. Set internally determines whether two values are different. The algorithm used is called "Same-value-zero equality", which is similar to the **exact equality** operator (`===`). The main difference is **`NaN` is equal to itself, while the exact equality operator considers `NaN` not to be equal to itself. **
let set = new Set(); let a = NaN; let b = NaN; set.add(a); set.add(b); set // Set {NaN} let set1 = new Set() set1.add(5) set1.add('5') console.log([...set1]) // [5, "5"]
Operation method:
add(value): New, equivalent to push in array.
delete(value): Delete the value in the collection if it exists.
has(value): Determine whether value exists in the collection.
clear(): Clear the collection.
Traversal method: Traversal method (traversal order is insertion order)
keys(): Returns an iterator containing all keys in the collection .
values(): Returns an iterator containing all values in the collection.
entries(): Returns a key-value iterator containing all elements in the Set object.
forEach(callbackFn, thisArg): Used to perform callbackFn operations on collection members. If the thisArg parameter is provided, this in the callback will be this parameter. There is no return value.
is a structure of a set of key-value pairs, with extremely fast search speed.
const m = new Map() const o = {p: 'haha'} m.set(o, 'content') m.get(o) // content m.has(o) // true m.delete(o) // true m.has(o) // false
Operation method:
Traversal method:
Set:
refers to the "set" structure
[value, value], the key value and the key name are consistent (or only the key value, no key name).
Map:
javascript video tutorial, web front-end】
The above is the detailed content of What is the difference between es6 set and map. For more information, please follow other related articles on the PHP Chinese website!