mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-21 19:16:23 +00:00
1.5 KiB
1.5 KiB
date | id | title |
---|---|---|
2020-10-12 | 0ad60ce3-4e34-490e-a565-a0ce330e6fc8 | JavaScript Maps |
Description
For sane people ES6 comes with a half assed
"solution" handy data structure called Map
which prevents the diy
shenanigans below.
Syntax
Basic operation
Single entries
const map = new Map();
const KEY = {};
map.set(KEY, 123);
console.log(map.get(KEY)); // 123
console.log(map.has(KEY)); // true
map.delete(KEY);
console.log(map.has(KEY)); // false
Array
const map = new Map([
[ 1, 'one' ],
[ 2, 'two' ],
[ 3, 'three' ],
]);
Iteration
Keys
const map = new Map([
[false, 'no'],
[true, 'yes'],
]);
for (const key of map.keys()) {
console.log(key);
}
Values
const map = new Map([
[false, 'no'],
[true, 'yes'],
]);
for (const value of map.values()) {
console.log(value);
}
Entries
const map = new Map([
[false, "no"],
[true, "yes"],
]);
for (const entry of map.entries()) {
console.log(entry[0], entry[1]);
}
Converting to Arrays
The spread operator (…) can turn an iterable into an Array
const map = new Map().set(false, 'no').set(true, 'yes');
console.log([...map.keys()]) // false, true
const map = new Map().set(false, 'no').set(true, 'yes');
console.log([...map])