Sets_and_Maps
Sets and maps
In ex6 ,two more data structures were finally introduced.
Set is iterable
Sets
Basic usage
Use new Set()
to creat a new set.
1 | const set = new Set(['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']); |
1 | const set = new Set('aniya'); |
The input must be iterable.
And the elements in a set is unique.
And there is no order of the elements. No index.
So there is no need to get a value form sets.
Methods of set
- .size
1 | const set //4= new Set('aniya'); |
- .has()
1 | const set = new Set('aniya'); |
To find out whether the set has the thing you want to know.
- .add()
1 | const set = new Set(); |
You can just add one at one time.
- .delete
1 | const set = new Set(); |
- .clear()
1 | const set = new Set('aniya'); |
To clear out the set.
Loop over the set
1 | const set = new Set('aniya'); |
Some usecases of sets
- To remove duplicated values of arrarys.
1 | const arr = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4]; |
And we can konw its size by the size
method.
Maps
Maps is alike to objects,data are also stored as key-value pairs.
The biggest diffrence is that keys in maps can be any type,such as number, string ,object and even another map.
While the keys in objects can only be string.
Creat a map
1 | const question = new Map([ |
The argument is a big arrary which contains many small arrarys which are compose of key-value pairs.
.set()
1 | let o = { |
- Calling the set method like this does not only update the map that’s called on,but it also returns the map.
So you can just do that like this:
1 | map.set(1, 'the first').set(o, o).set('key', 2); |
.get()
1 | console.log(map.get('key'));//2 |
.has()
.delete()
If you want to use an “Complex datatype” as an key ,you should store it in an variation first.
Wrong
1
2
3const map = new Map();
map.set([1, 2], 'this');
console.log(map.get([1, 2]));//undefinedBecause the two
[1,2]
is not the same object that is stored in heap.Right
1
2
3
4const map = new Map();
const arr = [1, 2];
map.set(arr, 'this');
console.log(map.get(arr)); //this
Convert a object into a map.
1 | newMap = new Map(Object.entries(objectName)); |
Loop over a map
1 | for(const [key,value] of mapName){ |