Set (Set)
- Is a data structure called collections (new in ES6)
- Array.from, or ES6… Extended operators)
const items = new Set([1.2.3.1]) const array = Array.from(items) console.log(array) / / [1, 2, 3] / / or const arr = [...items] console.log(arr) / / [1, 2, 3] Copy the code
- Is itself a constructor used to generate a Set data structure
new Set([iterable]) Copy the code
- Members are unique, unordered, and non-repetitive
const s = new Set([1.2.3.5.4.3.2.1]) //1 2 3 5 4 Copy the code
- [value, value], the key value is the same as the key name (or only the key value, no key name)
- Allows you to store a unique value of any type, either a primitive value or an object reference
new Set({a:"123".b:"1234"}){a:"123",b:"1234"} This is not iterable const s = new Set(a); s.add({a:"123".b:"1234"})// It works Copy the code
- You can iterate with for of
const s = new Set([1.2.3.5.4.3.2.1]) //1 2 3 5 4 for (let i of s) { console.log(i) // 1 2 3 5 4 } Copy the code
- When a value is added to a Set, no type conversion occurs
let s = new Set() s.add(1) s.add('1') console.log([...s]) / / / 1, "1" Copy the code
- The Set instance attributes are:
- Constructor: a constructor
- Size: number of elements
let set = new Set([1.2.3.5.4.3.2.1]) console.log(set.size) / / 3 console.log(set.length) // undefined Copy the code
- Note: There is no length attribute
- You can add, delete, has, and clear
- Add (value) : adds a value, which is equivalent to push in an array
- Delete (value) : deletes the value in the collection
- Has (value) : Determines whether a value exists in the set
- Clear () : Clears the collection
let set = new Set() set.add(1).add(2).add(3) set.has(1) // true set.has(4) // false set.delete(1) set.has(1) // false Copy the code
- Keys values entries forEach (Traversal order: insert order)
- Keys () : Returns an iterator containing all the keys in the collection
- Values () : Returns an iterator containing all the worth iterators in the setKeys with values () ()It’s the same thing becauseKey value and key nameIs consistent) as shown in the picture:
- Entries () : Returns a key-value iterator containing all the elements of the Set object
The key and value structure is shown in the screenshot belowCopy the code
4. ForEach (callbackFn, thisArg) : used to perform callbackFn on a collection member. If thisArg is provided, this in the callback would be this.No return value
- Set can be traversed by default, and the default iterator generator is the values() method
Set.prototype[Symbol.iterator] === Set.prototype.values // true Copy the code
- Set can use map and filter methods
- Intersect and Union can be easily implemented with Set.
let set1 = new Set([1.2.3.5]) let set2 = new Set([4.3.2.1]) let intersect = new Set([...set1].filter(value= > set2.has(value))) let union = new Set([...set1, ...set2]) console.log(intersect) // Set(3) {1, 2, 3} console.log(union) // Set(5) {1, 2, 3, 5, 4} Copy the code
WeakSet
- Members are objects
- Members are weak references that can be collected by the garbage collection mechanism and can be used to hold DOM nodes without causing memory leaks
- Can’t traverse
- The differences with Set are as follows:
- WeakSet can only store object references, not values, but both Set values and objects can be stored
- The object values stored in the WeakSet object are weakly referenced, that is, the garbage collection mechanism does not consider the application of WeakSet to the object. If there is no other variable or attribute referencing the object value, the object will be garbage collected (not considering the object still exists in the WeakSet), so, The number of member elements in the WeakSet object depends on whether the garbage collection mechanism is running. The number of members before and after the operation may be inconsistent. After the end of traversal, some members may not be taken (recycled by the garbage), and the WeakSet object cannot be traversed (ES6 specifies that WeakSet cannot be traversed). There’s no way to get all the elements it contains
- WeakSet instance attributes are:
- Any object that has an Iterable interface can be used as an argument
- The operation methods include :add, delete, has,Clear method does not have
- Add (value) : Add an element value to the WeakSet object
- Has (value) : Determines whether a Value is included in a WeakSet object
- Delete (value) : deletes the value of the element
- Clear () : Clears all elements, noting that this method is deprecated
var wst = new WeakSet(a)var obj = {} var abc = {} wst.add(window) wst.add(obj) wst.has(window) // true wst.has(abc) // false wst.delete(window) // true wst.has(window) // false Copy the code
The Map (dictionary)
- It’s a data structure called a dictionary
- It’s essentially a set of key-value pairs, sort of a set
- You can iterate, you can do a lot of things and you can convert to a lot of different data formats
- The Map instance attributes are:
- Constructor: a constructor
- Size: Returns the number of elements contained in the dictionary
const map = new Map([['name'.'long'], ['age'.12]]); map.size/ / 2 map.length /// undefined Copy the code
- Note: There is no length attribute
- The Map operation method has: set, get, has, delete, clear
- Set (key, value) : Adds a new element to the dictionary
- Get (key) : Finds a specific value by key and returns it
- Has (key) : Checks whether the key exists in the dictionary
- Delete (key) : removes the corresponding data from the dictionary by key
- Clear () : Removes all elements from this dictionary
const m = new Map(a)const o = {name: 'long'} m.set(o, 'liangliang') m.get(o) // liangliang m.has(o) // true m.delete(o) // true m.has(o) // false Copy the code
- Traversal methods are: the Keys and values, entries, forEach
- Keys() : Returns all key names contained in the dictionary as iterators
- Values () : Returns all values contained in the dictionary as iterators
- Entries () : Returns an iterator for all members
- ForEach (callbackFn,thisArg) : iterates through all members of the dictionary, performing callbackFn on the collection member. If thisArg is provided,this in the callback will be the thisArg argument, with no return value
const map = new Map([['name'.'long'], ['age'.16]]);console.log(map.entries())//MapIterator {"name" => "long", "age" => 16} console.log(map.keys())//MapIterator {"name", "age"} console.log(qmap.values())//MapIterator {"long", 16} const reporter = { report: function(key, value) { console.log("Key: %s, Value: %s", key, value); }};let map = new Map([['name'.'long'], ['age'.16]])// Note that the this of the forEach callback refers to reporter map.forEach(function(value, key, map) { this.report(key, value); }, reporter); // Key: name, Value: long // Key: age, Value: 16 Copy the code
- The default Map traverser interface (symbol. iterator property) is the entries method
const map = new Map() map[Symbol.iterator] === map.entries // true Map.prototype[Symbol.iterator] === Map.prototype.entries Copy the code
- Differences between sets and dictionaries:
- Common: Collections, dictionaries can store values that are not duplicated
- Differences: Collections store elements as [value, value], dictionaries as [key, value]
- Matters needing attention
- The Map structure only treats references to the same object as the same key, which is easy to mistake
const map = new Map(a); map.set(['a'].555); map.get(['a']) // undefined var scs = ['a']; map.set(scs , Awesome!); map.get(scs)/ / 666 // Set and get methods, ostensibly for the same key, are actually two values, // The memory address is different, so the get method cannot read the key, returns undefined, // The second example is fine Copy the code
- If the Map’s key is a value of a simple type (number, string, Boolean), the Map will treat the two values as one key as long as they are strictly equal, such as 0 and -0 being one key, and true and the string true being two different keys. Also,undefined and NULL are two different keys. Although NaN is not strictly equal to itself, Map treats it as the same key.
- The Map structure only treats references to the same object as the same key, which is easy to mistake
- Map and other data structures are converted as follows:
- Turn the Map Array
const map = new Map([[1.1], [2.2], [3.3]]) console.log([...map]) // [[1, 1], [2, 2], [3, 3]] Copy the code
- Array to the Map
const map = new Map([[1.1], [2.2], [3.3]]) console.log(map) // Map {1 => 1, 2 => 2, 3 => 3} Copy the code
- Turn the Map Object
- Since the key names of Object are strings and the key names of Map are objects, non-string keys are converted to string keys during conversion.
function mapToObj(map) { let obj = Object.create(null) for (let [key, value] of map) { obj[key] = value } return obj } const map = new Map().set('name'.'long').set('age'.16) mapToObj(map) // {name: "long", age: "16"} Copy the code
- Turn the Object Map
function objToMap(obj) { let map = new Map(a)for (let key of Object.keys(obj)) { map.set(key, obj[key]) } return map } objToMap({'name': 'long'.'age': 16}) // Map {"name" => "long", "age" => 16} Copy the code
- The Map to JSON
function mapToJson(map) { return JSON.stringify([...map]) } let map = new Map().set('name'.'LONG').set('age'.16) mapToJson(map) // [["name","LONG"],["age",16]] Copy the code
- JSON to turn the Map
function objToMap(obj) { let map = new Map(a)for (let key of Object.keys(obj)) { map.set(key, obj[key]) } return map } function jsonToStrMap(jsonStr) { return objToMap(JSON.parse(jsonStr)); } jsonToStrMap('{"name": "long", "age": 16}') // Map {"name" => "long", "age" => 16} Copy the code
- Turn the Map Array
WeakMap
- Only objects (except null) are accepted as key names, and values of other types are not accepted as key names.
- The key name is a weak reference, the key value can be arbitrary, the object that the key name refers to can be garbage collected, in which case the key name is invalid.
- The methods are get, set, has, and delete.
- Note that WeakMap weakly references only the key name, not the key value. Key values are still normal references.
- In WeakMap, the reference of each key to its referenced object is weak. If there is no other reference and the key references the same object, the object will be garbage collected (the corresponding key becomes invalid). Therefore, the key of WeakMap is not enumerable.
- Properties:
- Constructor: a constructor
- Methods:
- Has (key) : checks whether there is an object associated with the key
- Get (key) : returns the object associated with the key (undefined)
- Set (key) : Sets a group of key associated objects
- Delete (key) : deletes the object associated with the key
let myElement = document.getElementById('logo'); let myWeakmap = new WeakMap(a); myWeakmap.set(myElement, {timesClicked: 0}); myElement.addEventListener('click'.function() { let logoData = myWeakmap.get(myElement); logoData.timesClicked++; }, false); Copy the code
conclusion
- These concepts are newly added, and it is difficult to remember them all at once. Our best memory is to use them, and we can use them successfully in our daily work
- Finally, if you like it, you can give it a thumbs up. Thank you